数据控制器
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.我错过了什么?
答案 0 :(得分:3)
您正在创建UserPick
的多个实例,不要这样做
我建议使用单例类来确保始终访问相同的Core Data堆栈组件。
将其添加到DataController
类
DataController
然后将class var sharedController : DataController {
struct Singleton {
static let instance = DataController()
}
return Singleton.instance
}
更改为
uploadToCoreData()