我正在检索一些JSON并将其存储在一个数组中。然后在一个调度块中,我遍历数组并调用一个单独的方法将每个数组项插入到Core Data中。像这样:
dispatch_async(dispatch_get_main_queue(), { [unowned self] in
for result in jsonCategoriesArray {
if let category = NSEntityDescription.insertNewObjectForEntityForName("Category", inManagedObjectContext: CoreDataStack.sharedInstance.managedObjectContext) as? Category {
self.insertCategory(category, usingJSON: result)
}
}
self.saveCoreDataContext()
self.loadSavedCategories()
})
这是插入方法:
private func insertCategory(category: Category, usingJSON json: JSON) {
let formatter = NSNumberFormatter()
formatter.generatesDecimalNumbers = true
category.id = (formatter.numberFromString(json["ID"].stringValue) as? NSDecimalNumber)!
category.categoryID = (formatter.numberFromString(json["IDKategori"].stringValue) as? NSDecimalNumber)!
category.title = json["KategoriBaslik"].stringValue
category.subCategoryCount = (formatter.numberFromString(json["AltKategoriSayi"].stringValue) as? NSDecimalNumber)!
guard let url = NSURL(string: json["KategoriResim"].stringValue) else {
return
}
NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
guard let httpUrlResponse = response as? NSHTTPURLResponse where httpUrlResponse.statusCode == 200,
let mimeType = response?.MIMEType where mimeType.hasPrefix("image"),
let data = data where error == nil
else {
print("Problem downloading the image of the category with id: \(category.id) and name: \(category.title)")
return
}
dispatch_async(dispatch_get_main_queue()) { [unowned self] in
category.logo = data
self.saveCoreDataContext()
NSNotificationCenter.defaultCenter().postNotificationName("CategoryUpdate", object: nil)
}
}.resume()
}
唯一的问题是使用NSURLSession
的图像下载会多次导致以下错误:
2016-07-07 12:33:21.284 En Yakın[24040:1541295] CoreData: error: Mutating a managed object 0x790995a0 <x-coredata:///Category/t045D239A-9032-4B07-B870-46AA156B1D9B15> (0x79099560) after it has been removed from its context.
图像是大约8 KB的缩略图,存储为Binary Data
。我该怎么办呢?