2016-01-26 156 views
4

數據控制器核心數據:數據不存儲到數據庫(SWIFT)

class DataController { 
let model = "GoodiesCoreData" 


private lazy var applicationDocumentsDirectory: NSURL = { 
    let urls = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask) 
    return urls[urls.count-1] 
}() 

// ***** 
// ***** DocumentDirectory is the recommended place to store users' data ***** 
// ***** 



private lazy var managedObjectModel: NSManagedObjectModel = { 
    let modelURL = NSBundle.mainBundle().URLForResource(self.model, withExtension: "momd")! 
    return NSManagedObjectModel(contentsOfURL: modelURL)! 
}() 


// Store coordinator mediates the object model and the persistent store 

private lazy var persistenceStoreCoordinator: NSPersistentStoreCoordinator = { 
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) 
    let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(self.model) 

    do { 
     let options = [NSMigratePersistentStoresAutomaticallyOption: true] 

     try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options) 
    } 
    catch { 
     fatalError("Error adding persistence store") 
    } 

    return coordinator 
}() 


lazy var managedObjectContext: NSManagedObjectContext = { 
    var context = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType) 
    context.persistentStoreCoordinator = self.persistenceStoreCoordinator 
    return context 
}() 


func saveContext() { 
    if managedObjectContext.hasChanges { 
     do { 
      try managedObjectContext.save() 
     } 
     catch { 
      print("Error saving context") 
      abort() 
     } 
    } 
} 
} 

我的實體 enter image description here

插入函數

func uploadToCoreData() { 
    for goodies in datas{ //4 datas 
     let moc = DataController().managedObjectContext 
     let corePhoto = NSEntityDescription.insertNewObjectForEntityForName("Photo", inManagedObjectContext: moc) as! Photo 

     let image = UIImageJPEGRepresentation(goodies.croppedPhoto!, 1) 
     corePhoto.photo = image 
     corePhoto.qty = goodies.value 

     let coreUser = NSEntityDescription.insertNewObjectForEntityForName("User", inManagedObjectContext: moc) as! User 
     coreUser.userId = userId 

     let coreCart = NSEntityDescription.insertNewObjectForEntityForName("Cart", inManagedObjectContext: moc) as! Cart 
     coreCart.cartId = cartId 
     coreCart.productName = productName 
     coreCart.price = price 
     coreCart.quantity = quantity 
     coreCart.cartToUser = coreUser 

     corePhoto.photoToCart = coreCart 

     print(corePhoto.qty) 

    } 

    DataController().saveContext() 

    let request = NSFetchRequest(entityName: "Photo") 
    let photoCount = DataController().managedObjectContext.countForFetchRequest(request, error: NSErrorPointer.init()) 


    print("total photo: \(photoCount)") 


} 

我是試圖插入數據uploadToCoreData()功能。它似乎沒關係,因爲它不打印「錯誤保存上下文」,當我使用,但是當我提取的數據打印「總照片:0」它應該是4.我錯過了什麼?

回答

3

你正在創建的DataController多個實例,不這樣做,

我建議使用一個單獨的類,以確保始終可以訪問相同的核心數據堆棧組件。

一下添加到DataController

class var sharedController : DataController { 
    struct Singleton { 
    static let instance = DataController() 
} 
    return Singleton.instance 
} 

然後更改uploadToCoreData()

func uploadToCoreData() { 
    let dataController = DataController.sharedController 
    let moc = dataController.managedObjectContext 
    for goodies in datas{ //4 datas 

     let corePhoto = NSEntityDescription.insertNewObjectForEntityForName("Photo", inManagedObjectContext: moc) as! Photo 

     let image = UIImageJPEGRepresentation(goodies.croppedPhoto!, 1) 
     corePhoto.photo = image 
     corePhoto.qty = goodies.value 

     let coreUser = NSEntityDescription.insertNewObjectForEntityForName("User", inManagedObjectContext: moc) as! User 
     coreUser.userId = userId 

     let coreCart = NSEntityDescription.insertNewObjectForEntityForName("Cart", inManagedObjectContext: moc) as! Cart 
     coreCart.cartId = cartId 
     coreCart.productName = productName 
     coreCart.price = price 
     coreCart.quantity = quantity 
     coreCart.cartToUser = coreUser 

     corePhoto.photoToCart = coreCart 

     print(corePhoto.qty) 

    } 

    dataController.saveContext() 

    let request = NSFetchRequest(entityName: "Photo") 
    let photoCount = moc.countForFetchRequest(request, error: NSErrorPointer.init()) 

    print("total photo: \(photoCount)") 
}