我使用单例来处理数组等。跨应用程序中的视图。
为了初始化单例和NSManagedObjectContext
,以便我可以获取对象,我使用:
+(DataControllerSingleton *)singleDataController
{
static DataControllerSingleton * single=nil;
@synchronized(self)
{
if(!single)
{
single = [[DataControllerSingleton alloc] init];
NSManagedObjectContext *context = [single.fetchedResultsController managedObjectContext];
single.masterCareList = [[NSMutableArray alloc] init];
}
}
return single;
}
当我插入一个新对象时,该对象不会出现在显示功能中,直到我重新启动应用程序。我通过这个方法在单例类中插入新对象:
- (void)insertNewObject:(Care *)care
{
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:
[entity name] inManagedObjectContext:self.managedObjectContext];
NSString *fileName = care.pictureURL;
NSString *text = care.causeText;
NSDate *date = care.date;
NSData *imgData = care.imageData;
[newManagedObject setValue:fileName forKey:@"urlPath"];
[newManagedObject setValue:text forKey:@"name"];
[newManagedObject setValue:date forKey:@"date"];
[newManagedObject setValue:imgData forKey:@"imageData"];
// Save the context.
[self saveContext];
NSError *error = nil;
if (![context save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should
not use this function in a shipping application, although it may be useful during
development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
我的 count 方法是我可以告诉在我重新启动应用程序之前不包含新对象的方法。count 方法也在单例中。
- (NSUInteger)countOfList
{
NSArray *fetchedData = [_fetchedResultsController fetchedObjects];
return [fetchedData count];
}
调用单例时,我使用:
DataControllerSingleton *singletonData = [DataControllerSingleton singleDataController];
[singletonData insertNewObject:care];
managedObjectContext
财产:
。H:
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
米:
@implementation DataControllerSingleton
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
为什么我的新对象在我重新启动应用程序之前不会显示在 ex count 中?
我是否以某种方式使用具有不同上下文的不同线程,或者不同的 fethedResultsController 或不同的单例(不应该是可能的吗?)?
我添加了这两行,它们不包含在生成的 CoreData Stack 中,现在可以正常工作了。
在单例标题中:
@interface DataControllerSingleton : NSObject <NSFetchedResultsControllerDelegate>
在实施文件中,
(NSFetchedResultsController *)fetchedResultsController {
_fetchedResultsController.delegate = self;