未保存Ios核心数据
我使用的是核心数据,我遇到了一个问题。当我保存数据且应用程序仍在运行时,我可以查看并获取已保存的数据 一旦应用程序关闭,所有字段都将删除,只保存对象。我可以在saveContext方法中看到这一点。 第一次启动时,当应用程序关闭时,saveContext方法被激活。我可以看到managedObjectContext对象正在插入新对象。 下次打开应用程序时,managedObjectContext会更新对象,以便我知道它会保存对象,但当我尝试检索对象时,它会找到 以下是插入对象的方式:未保存Ios核心数据,ios,objective-c,core-data,Ios,Objective C,Core Data,我使用的是核心数据,我遇到了一个问题。当我保存数据且应用程序仍在运行时,我可以查看并获取已保存的数据 一旦应用程序关闭,所有字段都将删除,只保存对象。我可以在saveContext方法中看到这一点。 第一次启动时,当应用程序关闭时,saveContext方法被激活。我可以看到managedObjectContext对象正在插入新对象。 下次打开应用程序时,managedObjectContext会更新对象,以便我知道它会保存对象,但当我尝试检索对象时,它会找到 以下是插入对象的方式: AppDe
AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
self.managedObjectContext = appDelegate.managedObjectContext;
@try {
UserData *userData =[NSEntityDescription insertNewObjectForEntityForName:[UserTable tableName] inManagedObjectContext:self.managedObjectContext];
//Insert Values
userData.facebookId=user.id;
userData.name=user.name;
userData.picoAccessToken=[PicoApiManager sharedInstance].accessToken;
userData.picoExpire=[PicoApiManager sharedInstance].expires;
userData.latitude=[NSNumber numberWithDouble:user.latitude];
userData.longitude=[NSNumber numberWithDouble:user.longitude];
userData.pushId=user.pushId;
userData.isActive=[NSNumber numberWithBool:activeStatus];
}
@catch (NSException *exception) {
NSLog(@"Insert exception - %@", exception.description);
}
或
这是应用程序代理功能:
- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext 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]);
}
}
}
#pragma mark - Core Data stack
// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return _managedObjectContext;
}
// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Pico-Db" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Pico.sqlite"];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
这就是我试图获取数据的方式:
AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
//2
// initializing NSFetchRequest
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
//Setting Entity to be Queried
NSEntityDescription *entity = [NSEntityDescription entityForName:[UserTable tableName] inManagedObjectContext:appDelegate.managedObjectContext];
[fetchRequest setEntity:entity];
NSError* error;
// Query on managedObjectContext With Generated fetchRequest
NSArray *fetchedRecords = [appDelegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (fetchedRecords.count >0) {
return YES;
}
return NO;
插入数据后必须调用
-[AppDelegate saveContext]
,以便CoreData将更改持久化到磁盘。NSManagedObjectContext
将在内存中存储更改,以便在应用程序仍处于活动状态时,您可以访问数据。但是,一旦应用程序终止,除非您调用-[AppDelegate saveContext]
,否则这些更改将不会持久化
在第一个示例中尝试以下操作:
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
self.managedObjectContext = appDelegate.managedObjectContext;
@try {
UserData *userData = [NSEntityDescription insertNewObjectForEntityForName:[UserTable tableName] inManagedObjectContext:self.managedObjectContext];
//Insert Values
userData.facebookId=user.id;
userData.name=user.name;
userData.picoAccessToken=[PicoApiManager sharedInstance].accessToken;
userData.picoExpire=[PicoApiManager sharedInstance].expires;
userData.latitude=[NSNumber numberWithDouble:user.latitude];
userData.longitude=[NSNumber numberWithDouble:user.longitude];
userData.pushId=user.pushId;
userData.isActive=[NSNumber numberWithBool:activeStatus];
} @catch (NSException *exception) {
NSLog(@"Insert exception - %@", exception.description);
}
// SAVE CONTEXT:
[appDelegate saveContext];
在第二个示例中尝试以下操作:
for (Picture *picture in Pictures) {
// Checks if inserted picture is already inside the table
AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
self.managedObjectContext = appDelegate.managedObjectContext;
@try {
PictureData *pictureData = [NSEntityDescription insertNewObjectForEntityForName:[PicturesTable tableName]inManagedObjectContext:self.managedObjectContext];
//Insert Values
pictureData.url=picture.source;
pictureData.isNew=[NSNumber numberWithBool:YES];
pictureData.isPick=[NSNumber numberWithBool:NO];
pictureData.timeTaken=picture.time_taken;
pictureData.albumData=[self getActiveAlbum];
} @catch (NSException *exception) {
NSLog(@"Insert exception - %@", exception.description);
}
}
// SAVE CONTEXT:
[appDelegate saveContext];
要创建提取请求,请执行以下操作:
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"YourEntityName"];
request.sortDescriptors = [NSSortDescriptor sortDescriptorWithKey:@"attributeName" ascending:YES];
request.predicate = [NSPredicate predicateWithFormat:@"attribute == %@", 13];
NSError *error = nil; //
NSArray *results = [appDelegate.managedObjectContext executeFetchRequest:request error:&error];
if (!results) {
NSLog(@"Error performing fetch request: %@", error.localizedDescription);
}
return ([results count] > 0); // There are more efficient ways of getting count from CoreData
在应用程序终止之前,在applicationWillTerminate中,我正在调用saveContext方法。那个电流?或者我每次插入数据时都需要调用此函数?
applicationWillTerminate
不保证被调用。不应依赖它来保存您的NSManagedObjectContext
。上下文应该在插入数据后保存,或者在应用程序中的下一个逻辑点保存。嘿,抱歉,但由于某些原因,它没有帮助。我用来获取信息的代码可以吗?请看我更新的答案。当您只需将实体名称传递给NSFetchRequest
初始值设定项时,不确定为什么需要麻烦地创建NSEntityDescription
。
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"YourEntityName"];
request.sortDescriptors = [NSSortDescriptor sortDescriptorWithKey:@"attributeName" ascending:YES];
request.predicate = [NSPredicate predicateWithFormat:@"attribute == %@", 13];
NSError *error = nil; //
NSArray *results = [appDelegate.managedObjectContext executeFetchRequest:request error:&error];
if (!results) {
NSLog(@"Error performing fetch request: %@", error.localizedDescription);
}
return ([results count] > 0); // There are more efficient ways of getting count from CoreData