4
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()
}
}
}
}
插入函數
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.我錯過了什麼?