我有一个表,它使用NSFetchedResultsController来填充它的数据。当我刷新我的表时,我需要更新所有50多个项目,所以我执行以下操作:我调用返回JSON数据的服务器,将“media”对象存储到数组中,循环遍历此数组并单独存储每个对象到核心数据(在后台线程中),然后重新加载表。这很好用。但是有一个重大问题。
由于循环遍历大型数组并将每个对象单独存储到核心数据,有时保存到数据库的步骤需要7秒以上。在执行此步骤时,当我从服务器获取其他数据时,响应时间会大大延迟。在保存过程完成之前,我无法获取新数据。我很困惑,因为这应该在后台线程中完成,而不是阻止其他服务器调用。
为什么将数据保存到bg中的核心数据会导致我的响应时间延迟?有没有更好的方法将大型数组存储到核心数据而不会中断任何响应?
//Refreshing User Table method
class func refreshUserProfileTable(callback: (error: NSError?) -> Void) {
//getProfile fetches data from server
ProfileWSFacade.getProfile(RequestManager.userID()!) {
(profile, isLastPage, error) -> () in
DataBaseManager.sharedInstance.saveInBackground({ (backgroundContext) in
let mediaList = profile?["media"] as? Array<JSONDictionary>
if let mediaList = mediaList {
//Response time is delayed when this loop is executing
for media in mediaList {
DataBaseManager.sharedInstance.storeObjectOfClass(Media.self, dict: media, context: backgroundContext)
}
}
}, completion: {
callback(error: error)
})
}
}
//MARK: Core data methods:
//Save in background method in Database manager
func saveInBackground(
block: (backgroundContext: NSManagedObjectContext) -> Void,
completion: (Void->Void)? = nil)
{
let mainThreadCompletion = {
if let completion = completion {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion()
})
}
}
backgroundContext.performBlock { () -> Void in
guard RequestManager.userID() != nil else {
mainThreadCompletion()
return
}
block(backgroundContext: self.backgroundContext)
if RequestManager.userID() != nil {
_ = try? self.backgroundContext.save()
DataBaseManager.sharedInstance.save()
}
mainThreadCompletion()
}
}
//Stores class object
func storeObjectOfClass<T: NSManagedObject where T: Mappable>(
entityClass:T.Type,
dict: JSONDictionary,
context: NSManagedObjectContext? = nil) -> T
{
let context = context ?? mainManagedObjectContext
let predicate = NSPredicate(format: "%K LIKE %@", entityClass.primaryKey(), entityClass.primaryKeyFromDict(dict))
let requestedObject = DataBaseManager.createOrUpdateFirstEntity(
entityType: T.self,
predicate: predicate,
context: context) { (entity) -> () in
entity.populateFromDictionary(dict)
}
return requestedObject
}
//Creates or updates core data entity
class func createOrUpdateFirstEntity<T: NSManagedObject>(
entityType entityType: T.Type,
predicate: NSPredicate,
context: NSManagedObjectContext,
entityUpdateBlock:(entity: T) -> ()) -> T
{
guard DataBaseManager.sharedInstance.doPersistentStoreAvailible() else { return T() }
let desc = NSEntityDescription.entityForName(String(entityType), inManagedObjectContext: context)!
let existingEntityRequest = NSFetchRequest()
existingEntityRequest.entity = desc
existingEntityRequest.predicate = predicate
let requestedObject = try? context.executeFetchRequest(existingEntityRequest).first
if let requestedObject = requestedObject as? T {
entityUpdateBlock(entity: requestedObject)
return requestedObject
} else {
let newObject = T(entity: desc, insertIntoManagedObjectContext: context)
entityUpdateBlock(entity: newObject)
return newObject
}
}
答案 0 :(得分:2)
我发现.performBlock
遵循FIFO规则,先进先出。这意味着块将按照它们放入内部队列的顺序执行:SO Link。因此,下一个休息调用将等到第一个块完成后再保存,然后进行回调。实际的响应时间并不慢,只是因为FIFO而节省了时间。
解决方案是使用不同的NSManagedContext进行配置文件加载,而不是使用用于所有后台调用的NSManagedContext。
let profileContext: NSManagedObjectContext
//Instead of calling saveInBackground, we save to saveInProfileContext, which wont block other rest calls.
func saveInProfileContext(
block: (profileContext: NSManagedObjectContext) -> Void,
completion: (Void->Void)? = nil)
{
let mainThreadCompletion = {
if let completion = completion {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion()
})
}
}
profileContext.performBlock { () -> Void in
guard RequestManager.userID() != nil else {
mainThreadCompletion()
return
}
block(profileContext: self.profileContext)
if RequestManager.userID() != nil {
_ = try? self.profileContext.save()
DataBaseManager.sharedInstance.save()
}
mainThreadCompletion()
}
}