【发布时间】:2016-08-01 03:29:12
【问题描述】:
您好,我正在使用 Core Data IOS 为目标 C 使用神奇的记录库。该库有许多 NSManageObjectContext 启动。我们应该使用什么来保持应用性能和良好的用户体验?
有很多
+ [NSManagedObjectContext MR_newContext]: Sets the default context as it's parent context. Has a concurrency type of NSPrivateQueueConcurrencyType.
+ [NSManagedObjectContext MR_newMainQueueContext]: Has a concurrency type of NSMainQueueConcurrencyType.
+ [NSManagedObjectContext MR_newPrivateQueueContext]: Has a concurrency type of NSPrivateQueueConcurrencyType.
+ [NSManagedObjectContext MR_newContextWithParent:…]: Allows you to specify the parent context that will be set. Has a concurrency type of NSPrivateQueueConcurrencyType.
+ [NSManagedObjectContext MR_newContextWithStoreCoordinator:…]: Allows you to specify the persistent store coordinator for the new context. Has a concurrency type of NSPrivateQueueConcurrencyType.
什么上下文启动是好的?
例如此函数处理 JSON 响应并在成功接收到响应时将记录保存到数据库
NSManagedObjectContext *localContext = [NSManagedObjectContext MR_context];
[Stamp MR_truncateAllInContext:localContext];
[responseJSON[@"root"] enumerateObjectsUsingBlock:^(id attributes, NSUInteger idx, BOOL *stop) {
Stamp *stamp = [Stamp MR_createEntityInContext:localContext];
[stamp setOrderingValue:idx];
[stamp updateWithApiRepresentation:attributes];
}];
[localContext MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
if (completionBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock(!error, error);
});
}
}];
这个函数执行获取请求
+ (NSArray *)yearsDropDownValues
{
NSManagedObjectContext *moc = [NSManagedObjectContext MR_rootSavingContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [Stamp entityInManagedObjectContext:moc];
request.entity = entity;
request.propertiesToFetch = @[StampAttributes.year];
request.returnsDistinctResults = YES;
request.resultType = NSDictionaryResultType;
request.sortDescriptors = @[[[NSSortDescriptor alloc] initWithKey:StampAttributes.year ascending:NO]];
NSArray *years = [moc executeFetchRequest:request error:nil];
NSMutableArray *res = [NSMutableArray array];
for (NSDictionary *year in years) {
[res addObject:@{@"code": [NSString stringWithFormat:@"%@ Collections", year[@"year"]], @"value": year[@"year"] }];
}
return res;
}
非常感谢任何帮助。谢谢
【问题讨论】:
-
好的,所以对于第一个,最好使用像你正在做的私有队列上下文。对于第二个,最好使用
MR_defaultContext,因为我认为您获取的值是用于 UI。 -
所以我们应该改变这个 NSManagedObjectContext *moc = [NSManagedObjectContext MR_rootSavingContext];到 NSManagedObjectContext *moc = [NSManagedObjectContext MR_defaultContext];几乎所有的 fetch 请求都应该使用 MR_defaultContext?
-
不是全部抓取,但是如果您抓取的数据是为了在屏幕上显示,那么在
MR_defaultContext中进行,但除了抓取之外不要做任何事情(如插入、更新或删除)在这种情况下。
标签: ios objective-c magicalrecord