核心数据:数据不存储到数据库(swift)
Posted
技术标签:
【中文标题】核心数据:数据不存储到数据库(swift)【英文标题】:Core Data: Data does not store to database (swift) 【发布时间】:2016-05-03 01:04:00 【问题描述】:数据控制者
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。我错过了什么?
【问题讨论】:
【参考方案1】:您正在创建DataController
的多个实例,不要这样做
我建议使用单例类来确保始终访问相同的 Core Data 堆栈组件。
将此添加到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)")
【讨论】:
以上是关于核心数据:数据不存储到数据库(swift)的主要内容,如果未能解决你的问题,请参考以下文章