我编写了一个ios应用程序,以便将数据保存到核心数据,然后使用以下代码获取它:
NSManagedObjectContext *context = [self managedObjectContext];
NSError *error;
NSManagedObject *failedBankInfo = [NSEntityDescription
insertNewObjectForEntityForName:@"UserData"
inManagedObjectContext:context];
[failedBankInfo setValue:[NSNumber numberWithInt:1] forKey:@"userId"];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"UserData" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *info in fetchedObjects) {
NSLog(@"Name: %@", [info valueForKey:@"userId"]);
}
这里没问题。但在我关闭我的应用程序并将setvalue修改为2之后,我只收到最后一个数据2.早期数据(1)被删除。
即使在我关闭应用程序后,我该怎么做才能保留数据条目。
谢谢!
答案 0 :(得分:2)
您需要创建UIManagedDocument
以保存核心数据信息。我通常创建UIManagedDocument
作为类的属性。对于示例,我创建了一个名为UIManagedDocument
的{{1}}:
theManagedDocument
然后我创建了一个名为NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:@"DocumentName"];
self.theManagedDocument = [[UIManagedDocument alloc] initWithFileURL:url];
if([[NSFileManager defaultManager] fileExistsAtPath:[url path]])
{
[theManagedDocument openWithCompletionHandler:^(BOOL success){
if(success) [self documentIsReady];
if(!success) NSLog(@"Couldn't Open Document");
}];
}
else
{
[theManagedDocument saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success){
if(success) [self documentIsReady];
if(!success) NSLog(@"Couldn't Create Document");
}];
}
的方法,该方法在成功创建或打开文档时被调用(如果文档已经存在则打开,否则创建)。我还将上下文保留为属性。这里称为documentIsReady
。我还在你的代码中添加了:
context
完成后,您将需要关闭文档:
- (void) documentIsReady
{
if(self.theManagedDocument.documentState == UIDocumentStateNormal)
{
self.context = self.theManagedDocument.managedObjectContext;
NSError *error;
NSManagedObject *failedBankInfo = [NSEntityDescription
insertNewObjectForEntityForName:@"UserData"
inManagedObjectContext:self.context];
[failedBankInfo setValue:[NSNumber numberWithInt:1] forKey:@"userId"];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"UserData" inManagedObjectContext:self.context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [self.context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *info in fetchedObjects) {
NSLog(@"Name: %@", [info valueForKey:@"userId"]);
}
}
}
答案 1 :(得分:1)
您没有保存新记录。
[self.managedObjectContext save:nil];