【发布时间】:2012-02-21 08:52:42
【问题描述】:
到目前为止,我一直在使用共享的 Coredata 实例。在视图控制器中我会调用[[Storage instance] managedObjectContext] 在视图控制器中传递!
你说我可能是大错特错?请告诉我为什么。
我注意到在大多数示例中,viewController 在头文件中的 @private 中都有 managedObjectContexts。为什么我们这里需要私人电话?
最后我们声明一下
NSManagedObjectContext *_managedObjectContext;
@property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
然后在 viewController.m 中
@synthesize managedObjectContext = _managedObjectContext;
“_”managedObjectContext有什么意义。为什么下划线?
最后,这一切会如何影响 iCloud?作者在一篇教程中说,
ivars 应该是私有的,并且所有代码都非常重要 总是通过访问器方法来确保这些是 正确初始化。如果没有有趣的 _,那么 KVC 可能会“帮助”我们 太多了。使用 iCloud 异步导入数据,还有更多 时间和多线程问题
没有有趣的_ ...请解释这里发生的事情..
@interface LStorage : NSObject {
@private
NSString *identifier;
NSManagedObjectContext *managedObjectContext;
NSManagedObjectModel *managedObjectModel;
NSPersistentStoreCoordinator *persistentStoreCoordinator;
}
@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
+ (LStorage *) instance;
in LStorage.m
+ (LStorage *) instance {
@synchronized(self) {
if (instance == nil) {
instance = [[LStorage alloc] initWithIdentifier:kIdentifier];
}
}
return instance;
}
//identifier is just used to name the mom model filename.
- (id) initWithIdentifier:(NSString *)anIdentifier {
self = [super init];
if(self != nil) {
identifier = anIdentifier;
}
return self;
}
- (NSManagedObjectContext *)managedObjectContext {
if (managedObjectContext != nil) {
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
// Make life easier by adopting the new NSManagedObjectContext concurrency API
// the NSMainQueueConcurrencyType is good for interacting with views and controllers since
// they are all bound to the main thread anyway
if(IOS_VERSION_GREATER_THAN_OR_EQUAL_TO(@"5.0")){
NSManagedObjectContext* moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[moc performBlockAndWait:^{
// even the post initialization needs to be done within the Block
[moc setPersistentStoreCoordinator: coordinator];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(mergeChangesFrom_iCloud:) name:NSPersistentStoreDidImportUbiquitousContentChangesNotification object:coordinator];
}];
managedObjectContext = moc;
}else{
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator:coordinator];
}
}
return managedObjectContext;
}
【问题讨论】:
标签: objective-c xcode core-data