我使用的是单与阵列等跨应用程序的视图工作。
要初始化单和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();
}
}
我的计数法是这样的,我可以告诉大家,不包括新的对象,直到我重新启动应用程序。 计数方法也是单身为好。
- (NSUInteger)countOfList
{
NSArray *fetchedData = [_fetchedResultsController fetchedObjects];
return [fetchedData count];
}
当调用单我使用:
DataControllerSingleton *singletonData = [DataControllerSingleton singleDataController];
[singletonData insertNewObject:care];
managedObjectContext
属性:
。H:
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
.M:
@implementation DataControllerSingleton
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
为什么我的新的对象出现在离计数,直到我重新启动应用程序?
我不知何故,我用不同的背景,或者不同的fethedResultsController或不同的单不同的线程(不应该是可能的吗?)?
我加这两条线,这是不包括在genereated CoreData堆栈,现在工作得很好。
在单头:
@interface DataControllerSingleton : NSObject <NSFetchedResultsControllerDelegate>
在实现文件中,
(NSFetchedResultsController *)fetchedResultsController {
_fetchedResultsController.delegate = self;