核心数据不能持久保存对象。

时间:2021-10-18 16:31:50

I'm new to Core Data and as such am not sure if I'm making a mistake. I've downloaded some data from a REST API and it successfully saves the JSON response to disk. I'm trying to process the data and save it persistently using Core Data.

我对核心数据不熟悉,因此我不确定自己是否犯了错误。我从REST API下载了一些数据,它成功地将JSON响应保存到磁盘。我正在尝试处理数据,并使用Core data保存它。

NSLog(@"inserted objects: %@", [managedObjectContext insertedObjects]);
    [managedObjectContext performBlockAndWait:^{
        NSError *error = nil;
        if (![managedObjectContext save:&error]) {
            NSLog(@"Unable to save context for class %@", className);
        } else {
            NSLog(@"saved all records!");
        }
    }];

I've successfully processed the JSON and added it to an NSManagedObjectContext. In the first line, it shows that I've successfully attempted to insert 2 objects.

我已经成功地处理了JSON并将其添加到NSManagedObjectContext中。在第一行,它显示我已经成功地插入了两个对象。

inserted objects: {(
    <User: 0xa259af0> (entity: User; id: 0xa259b70 <x-coredata:///User/t44BB97D0-C4B4-4BA6-BD25-13CEFDAE665F3> ; data: {
    email = "vishnu@vishnuprem.com";
    experience = "2013-07-20";
    "first_name" = Vishnu;
    id = 2;
    "job_title" = Developer;
    "last_name" = Prem;
    location = "";
    "phone_number" = "+6590091516";
    "profile_pic" = "";
    "thumbnail_profile_pic" = "";
    "user_id" = 2;
}),
    <User: 0xa25e460> (entity: User; id: 0xa25e4c0 <x-coredata:///User/t44BB97D0-C4B4-4BA6-BD25-13CEFDAE665F2> ; data: {
    email = "sanchitbareja@gmail.com";
    experience = "2013-07-20";
    "first_name" = Sanchit;
    id = 1;
    "job_title" = Developer;
    "last_name" = Bareja;
    location = "";
    "phone_number" = "+15106127328";
    "profile_pic" = "";
    "thumbnail_profile_pic" = "";
    "user_id" = 1;
})
)}

When I attempted [managedObjectContext save:&error], it does so successfully and print out "saved all records" as expected. However, when I go to my application .sqlite file and check for added objects, I realize that it hasn't added any objects to the db.

当我尝试[managedObjectContext save:&error]时,它成功地做到了,并按预期输出“保存所有记录”。但是,当我打开我的应用程序.sqlite文件并检查添加的对象时,我意识到它没有向db添加任何对象。

On app relaunch, I print out a list of objects that are already in the database and it confirms that I've none saved yet.

在app relaunch中,我打印出一个已经在数据库中的对象列表,它确认我还没有保存。

Does anyone know what's going on and why I'm not able to save the data persistently even though it looks like I've successfully created the 'User' objects that needs to be saved in the Core Data model.

有人知道发生了什么吗?为什么我不能持久地保存数据,尽管看起来我已经成功地创建了需要保存在Core data模型中的“User”对象。

EDIT:

编辑:

here is where I create the NSPersistentStoreCoordinator

这里是我创建NSPersistentStoreCoordinator的地方

// 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:@"RTModel.sqlite"];

    NSError *error = nil;
    NSLog(@"Test 1");
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSLog(@"Test 2");

    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&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.

         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.


         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.

         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

         * Performing automatic lightweight migration by passing the following dictionary as the options parameter:
         [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.

         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _persistentStoreCoordinator;
}

I have 3 contexts.

我有3个上下文。

  • masterManagedObjectContext

    masterManagedObjectContext

  • backgroundManagedObjectContext

    backgroundManagedObjectContext

  • newManagedObjectContext

    newManagedObjectContext

master is parent of both background and new. When I query the contexts like this:

master既是背景又是新事物的父类。当我查询这样的上下文时:

    NSError *error = nil;
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"User"];
    [request setSortDescriptors:[NSArray arrayWithObject:
                                 [NSSortDescriptor sortDescriptorWithKey:@"id" ascending:YES]]];
    [request setReturnsObjectsAsFaults:NO];
    NSArray *testArray = [[[RTCoreDataController sharedInstance] newManagedObjectContext] executeFetchRequest:request error:&error];

    for (User *obj in testArray) {
        NSLog(@"obj.id %@", obj.id);
    }

    NSLog(@"query records: %@",testArray);

master and background both return the correct obj.id in the NSLog as well as gives the output below for @"query records"

master和background都返回正确的obj。NSLog中的id,以及以下@“查询记录”的输出

   (
    "<User: 0xa3811d0> (entity: User; id: 0xa381230 <x-coredata:///User/t92BCED2D-CD17-49CC-9EBA-DF8F52F06A002> ; data: {\n    email = \"sanchitbareja@gmail.com\";\n    experience = \"2013-07-20\";\n    \"first_name\" = Sanchit;\n    id = 1;\n    \"job_title\" = Developer;\n    \"last_name\" = Bareja;\n    location = \"\";\n    \"phone_number\" = \"+15106127328\";\n    \"profile_pic\" = \"\";\n    \"thumbnail_profile_pic\" = \"\";\n    \"user_id\" = 1;\n})",
    "<User: 0xa382170> (entity: User; id: 0xa3820b0 <x-coredata:///User/t92BCED2D-CD17-49CC-9EBA-DF8F52F06A003> ; data: {\n    email = \"vishnu@vishnuprem.com\";\n    experience = \"2013-07-20\";\n    \"first_name\" = Vishnu;\n    id = 2;\n    \"job_title\" = Developer;\n    \"last_name\" = Prem;\n    location = \"\";\n    \"phone_number\" = \"+6590091516\";\n    \"profile_pic\" = \"\";\n    \"thumbnail_profile_pic\" = \"\";\n    \"user_id\" = 2;\n})"
)

however "new" returns (null) for the obj.id in NSLog and returns the following for @"query records":

然而,obj的“new”返回(null)。在NSLog中返回id,并返回以下@“查询记录”:

(
    "<User: 0xa2b08a0> (entity: User; id: 0x95aebe0 <x-coredata:///User/tBFCC6C5F-7D2C-4AA0-BA96-B806EE360A762> ; data: <fault>)",
    "<User: 0xa2b0910> (entity: User; id: 0xa4b9780 <x-coredata:///User/tBFCC6C5F-7D2C-4AA0-BA96-B806EE360A763> ; data: <fault>)"
)

7 个解决方案

#1


11  

From your code and the comments it seems that you are not saving the master context. Make sure you call

从您的代码和注释看来,您并没有保存主上下文。确保你叫

[managedObjectContext save:&error]; 

on all child contexts that save the data, and after that on the master context as well.

在保存数据的所有子上下文中,以及在主上下文中之后。

#2


9  

I just got done banging my head against essentially the same problem. A UITableViewController fetched a subclass of NSManagedObject from the NSManagedObjectContext, checked if an attribute was nil, and if it was downloaded the data, set that attribute, then saved the NSManagedObjectContext. Something like this:

我刚刚结束了我的头撞到同样的问题上。UITableViewController从NSManagedObjectContext中获取NSManagedObject的子类,检查属性是否为nil,如果下载数据,设置该属性,然后保存NSManagedObjectContext。是这样的:

MyManagedObject *mgObject = //get object from NSFetchResultsController
NSManagedObjectContext *mgObContext = mgObject.managedObjectContext;
if (!mgObject.data)
{
    mgObject.data = [NSData dataWithContentsOfURL:urlWithData];
    [mgObContext performBlock ^{
        NSError *saveError = nil;
        BOOL saveResult = [mgObContext save:&saveError];
        if (saveError || !saveResult)
        {
            NSLog(@"Save not successful..");
        }
    }];
}
//do something with myObject.data

The save function was giving a YES boolean return and saveError was remaining nil, but if I quit the app and relaunched, when my Core Data loaded up my NSManagedObject subclasses, the data attribute was nil, and when this UITableViewController came back up, it had to download the data again.

save函数给出一个YES boolean返回,saveError保持为nil,但是如果我退出app重新启动,当我的核心数据加载到NSManagedObject的子类时,数据属性为nil,当UITableViewController恢复时,它必须再次下载数据。

I couldn't really find a solution to this anywhere… reading through the Core Data documentation didn't help. The solution came to me when I considered the difference between the above code and my code that sets the attributes in the NSManagedObject subclass's factory methods, which is basically:

我在任何地方都找不到解决这个问题的方法……阅读核心数据文档没有任何帮助。当我考虑到上面的代码和设置NSManagedObject子类工厂方法中的属性的代码之间的差异时,我想到了解决方案。

MyManagedObject *mgObject = [NSEntityForDescription insertNewObjectForEntityName:@"MyManagedObject" inManagedContext:mgObContext];
mgObject.attribute1 = some value
mgObject.attribute2 = another value

The only difference is that I'm calling the factory methods from inside a [mgObContext performBlock:].

唯一的区别是,我是从[mgObContext performBlock:]内部调用工厂方法。

So the amended code is:

修改后的代码是:

MyManagedObject *mgObject = //get object from NSFetchResultsController
NSManagedObjectContext *mgObContext = mgObject.managedObjectContext;
if (!mgObject.data)
{
    [mgObContext performBlock: ^{
        mgObject.data = [NSData dataWithContentsOfURL:urlWithData];
        NSError *saveError = nil;
        BOOL saveResult = [mgObContext save:&saveError];
        if (saveError || !saveResult)
        {
            NSLog(@"Save not successful..");
        }
    }];
}
//do something with myObject.data

Which, thus far, is working perfectly. So I think anytime you made modifications to NSManagedObjects' attributes, you need to do so on the their NSManagedObjectContext's thread.

到目前为止,它运行得很好。所以我认为,每当你修改NSManagedObjects的属性时,你都需要在它们的NSManagedObjectContext线程上进行修改。

#3


5  

Figured I would also add some input to people who may have similar issues.

我想我也会给可能有类似问题的人增加一些投入。

In my experience, attempting to save objects that don't have sufficient fields filled out don't seem to persist when saving, and no errors seem to be thrown when this is the case. Always double check that your fields are being filled in as expected before the save fires.

在我的经验中,尝试保存没有填满足够字段的对象在保存时似乎不会持久,而且在这种情况下似乎不会抛出错误。在save点火之前,一定要检查字段是否按预期填充。

Another way to look at these types of issues is to flip the problem on its head. Maybe the object did in fact save, but the method in which you're verifying that they have in fact been saved is wrong. Often you might do this by querying CoreData for the record(s) using certain criteria. Double check that your criteria is correct and that it your query is actually returning what you expect.

看待这些问题的另一种方式是把问题抛到脑后。也许这个对象确实保存了,但是你正在验证它们是否被保存的方法是错误的。通常,您可以通过使用某些标准查询记录的CoreData来实现这一点。再次检查您的条件是否正确,以及您的查询是否实际返回您所期望的内容。

If it does not return what you expect, it could be due to your own errors, but it could also be that the array storing your results isn't storing them properly. I have run into cases before where I had to rename an NSArray because something about the array name was causing referencing issues, and thus the array could not point to the results I was expecting. Cheers.

如果它没有返回您期望的结果,这可能是由于您自己的错误,但也可能是存储结果的数组没有正确地存储它们。我以前遇到过必须重命名NSArray的情况,因为关于数组名的一些内容导致了引用问题,因此数组不能指向我预期的结果。欢呼。

#4


2  

I'm a beginner with iOS but I have done some example with CoreData to store users info.

我是iOS的初学者,但是我用CoreData做过一些例子来存储用户信息。

First, you need to create your model with your entity (I suppose you have already done). In my example, my entity is called "User".

首先,您需要使用实体创建模型(我认为您已经这样做了)。在我的示例中,我的实体称为“User”。

First, add a property similar to this

首先,添加类似的属性

NSManagedObjectContext *context;

to your ViewController class.

ViewController类。

Second, in your viewDidLoad method, add this two lines:

其次,在viewDidLoad方法中,添加以下两行:

AppDelegate *appdelegate = [[UIApplication sharedApplication]delegate];
context = [appdelegate managedObjectContext];

And third, store your info:

第三,储存你的信息:

NSEntityDescription *entitydesc = [NSEntityDescription entityForName:@"User" inManagedObjectContext:context];
NSManagedObject *newUser = [[NSManagedObject alloc]initWithEntity:entitydesc insertIntoManagedObjectContext:context];
[newUser setValue:(NSString *)[dictionary objectForKey:@"name"] forKey:@"name"];
[newUser setValue:(NSString *)[dictionary objectForKey:@"surname"] forKey:@"surname"];
...

NSError *error;
[context save:&error];

(I take my properties from a NSDictionary called dictionary)

(我从一个叫做dictionary的NSDictionary中获取属性)

To read your info:

阅读你的信息:

AppDelegate *appdelegate = [[UIApplication sharedApplication]delegate];
context = [appdelegate managedObjectContext];
NSEntityDescription *entitydesc = [NSEntityDescription entityForName:@"User" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entitydesc];

//NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NULL"];
[request setPredicate:nil];

NSError *error;
NSArray *matchingData = [context executeFetchRequest:request error:&error];
//NSArray *matchingData = [context executeFetchRequest:nil error:&error];

// If the user is not logged in previously
if (matchingData.count <=0 ){
    //self.displaylabel.text = @"No person find";
} else {
// If the user is already logged in
    for (NSManagedObject *obj in matchingData) {
        AppDataModel *appDataModel=[AppDataModel getInstance];
        appDataModel.appUserInfo = [User alloc]; 
        appDataModel.appUserInfo.name = [obj valueForKey:@"name"];
        appDataModel.appUserInfo.surname = [obj valueForKey:@"surname"];
    }
}

#5


2  

I know that this is not an answer to what the OP asked, but I wanted to share my experience about the same subject in case it will help someone else.

我知道这不是OP所要求的答案,但我想分享我对同一主题的经验,以防它对其他人有所帮助。

I had some issues with saving data persistently, anything seemed to help me fix it. The structure was very simple, an Entity with one field and one relationship (to-many). I made some changes to the class generated, NSMutableOrderedSet instead of NSOrderedSet.

我坚持不懈地保存数据,任何事情似乎都能帮我解决问题。结构非常简单,一个具有一个字段和一个关系(to-many)的实体。我对生成的类NSMutableOrderedSet做了一些更改,而不是NSOrderedSet。

I was not doing multi thread, or anything like that, just adding elements to the relationship. After saving, and re-launching the application, data just disappeared (elements added to the relationship).

我不是在做多线程,或者类似的东西,只是在关系中添加元素。保存并重新启动应用程序之后,数据就消失了(添加到关系中的元素)。

I ended up discovering that there is a property called updated. After adding the new element to the relationship, I checked if this property changed its value. It didn't. So I had to create another field in the Entity, a Boolean, just to be able to force the entity to be saved after adding elements to this relationship.

最后我发现有一个属性叫做update。在向关系中添加新元素之后,我检查这个属性是否改变了它的值。它没有。因此,我必须在实体中创建另一个字段,一个布尔值,这样就可以在添加元素后将实体保存起来。

entity.addObject(..)
entity.forceUpdate = true // without this line, it won't update
managedContext.save(..)

So I hope it helps anyone with the same problem, as I spent some time thinking that I was not saving it correctly..

所以我希望它能帮助有同样问题的人,因为我花了一些时间思考我没有正确地保存它。

#6


2  

Add this after you save your data :

保存数据后添加:

NSError *error = nil;
if (![managedObjectContext save:&error]) {
    NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}

#7


0  

After hours of debugging, I found that the reason my updates weren't being saved was because in my subclass of NSManagedObject I defined by properties w/ @synthesize instead of @dynamic.

经过数小时的调试,我发现之所以没有保存更新,是因为在NSManagedObject的子类中,我使用属性w/ @synthesize而不是@dynamic定义更新。

After I change it, it all saved as expected.

在我修改之后,它就像预期的那样被保存了下来。

Hope that helped someone.

希望帮助别人。

#1


11  

From your code and the comments it seems that you are not saving the master context. Make sure you call

从您的代码和注释看来,您并没有保存主上下文。确保你叫

[managedObjectContext save:&error]; 

on all child contexts that save the data, and after that on the master context as well.

在保存数据的所有子上下文中,以及在主上下文中之后。

#2


9  

I just got done banging my head against essentially the same problem. A UITableViewController fetched a subclass of NSManagedObject from the NSManagedObjectContext, checked if an attribute was nil, and if it was downloaded the data, set that attribute, then saved the NSManagedObjectContext. Something like this:

我刚刚结束了我的头撞到同样的问题上。UITableViewController从NSManagedObjectContext中获取NSManagedObject的子类,检查属性是否为nil,如果下载数据,设置该属性,然后保存NSManagedObjectContext。是这样的:

MyManagedObject *mgObject = //get object from NSFetchResultsController
NSManagedObjectContext *mgObContext = mgObject.managedObjectContext;
if (!mgObject.data)
{
    mgObject.data = [NSData dataWithContentsOfURL:urlWithData];
    [mgObContext performBlock ^{
        NSError *saveError = nil;
        BOOL saveResult = [mgObContext save:&saveError];
        if (saveError || !saveResult)
        {
            NSLog(@"Save not successful..");
        }
    }];
}
//do something with myObject.data

The save function was giving a YES boolean return and saveError was remaining nil, but if I quit the app and relaunched, when my Core Data loaded up my NSManagedObject subclasses, the data attribute was nil, and when this UITableViewController came back up, it had to download the data again.

save函数给出一个YES boolean返回,saveError保持为nil,但是如果我退出app重新启动,当我的核心数据加载到NSManagedObject的子类时,数据属性为nil,当UITableViewController恢复时,它必须再次下载数据。

I couldn't really find a solution to this anywhere… reading through the Core Data documentation didn't help. The solution came to me when I considered the difference between the above code and my code that sets the attributes in the NSManagedObject subclass's factory methods, which is basically:

我在任何地方都找不到解决这个问题的方法……阅读核心数据文档没有任何帮助。当我考虑到上面的代码和设置NSManagedObject子类工厂方法中的属性的代码之间的差异时,我想到了解决方案。

MyManagedObject *mgObject = [NSEntityForDescription insertNewObjectForEntityName:@"MyManagedObject" inManagedContext:mgObContext];
mgObject.attribute1 = some value
mgObject.attribute2 = another value

The only difference is that I'm calling the factory methods from inside a [mgObContext performBlock:].

唯一的区别是,我是从[mgObContext performBlock:]内部调用工厂方法。

So the amended code is:

修改后的代码是:

MyManagedObject *mgObject = //get object from NSFetchResultsController
NSManagedObjectContext *mgObContext = mgObject.managedObjectContext;
if (!mgObject.data)
{
    [mgObContext performBlock: ^{
        mgObject.data = [NSData dataWithContentsOfURL:urlWithData];
        NSError *saveError = nil;
        BOOL saveResult = [mgObContext save:&saveError];
        if (saveError || !saveResult)
        {
            NSLog(@"Save not successful..");
        }
    }];
}
//do something with myObject.data

Which, thus far, is working perfectly. So I think anytime you made modifications to NSManagedObjects' attributes, you need to do so on the their NSManagedObjectContext's thread.

到目前为止,它运行得很好。所以我认为,每当你修改NSManagedObjects的属性时,你都需要在它们的NSManagedObjectContext线程上进行修改。

#3


5  

Figured I would also add some input to people who may have similar issues.

我想我也会给可能有类似问题的人增加一些投入。

In my experience, attempting to save objects that don't have sufficient fields filled out don't seem to persist when saving, and no errors seem to be thrown when this is the case. Always double check that your fields are being filled in as expected before the save fires.

在我的经验中,尝试保存没有填满足够字段的对象在保存时似乎不会持久,而且在这种情况下似乎不会抛出错误。在save点火之前,一定要检查字段是否按预期填充。

Another way to look at these types of issues is to flip the problem on its head. Maybe the object did in fact save, but the method in which you're verifying that they have in fact been saved is wrong. Often you might do this by querying CoreData for the record(s) using certain criteria. Double check that your criteria is correct and that it your query is actually returning what you expect.

看待这些问题的另一种方式是把问题抛到脑后。也许这个对象确实保存了,但是你正在验证它们是否被保存的方法是错误的。通常,您可以通过使用某些标准查询记录的CoreData来实现这一点。再次检查您的条件是否正确,以及您的查询是否实际返回您所期望的内容。

If it does not return what you expect, it could be due to your own errors, but it could also be that the array storing your results isn't storing them properly. I have run into cases before where I had to rename an NSArray because something about the array name was causing referencing issues, and thus the array could not point to the results I was expecting. Cheers.

如果它没有返回您期望的结果,这可能是由于您自己的错误,但也可能是存储结果的数组没有正确地存储它们。我以前遇到过必须重命名NSArray的情况,因为关于数组名的一些内容导致了引用问题,因此数组不能指向我预期的结果。欢呼。

#4


2  

I'm a beginner with iOS but I have done some example with CoreData to store users info.

我是iOS的初学者,但是我用CoreData做过一些例子来存储用户信息。

First, you need to create your model with your entity (I suppose you have already done). In my example, my entity is called "User".

首先,您需要使用实体创建模型(我认为您已经这样做了)。在我的示例中,我的实体称为“User”。

First, add a property similar to this

首先,添加类似的属性

NSManagedObjectContext *context;

to your ViewController class.

ViewController类。

Second, in your viewDidLoad method, add this two lines:

其次,在viewDidLoad方法中,添加以下两行:

AppDelegate *appdelegate = [[UIApplication sharedApplication]delegate];
context = [appdelegate managedObjectContext];

And third, store your info:

第三,储存你的信息:

NSEntityDescription *entitydesc = [NSEntityDescription entityForName:@"User" inManagedObjectContext:context];
NSManagedObject *newUser = [[NSManagedObject alloc]initWithEntity:entitydesc insertIntoManagedObjectContext:context];
[newUser setValue:(NSString *)[dictionary objectForKey:@"name"] forKey:@"name"];
[newUser setValue:(NSString *)[dictionary objectForKey:@"surname"] forKey:@"surname"];
...

NSError *error;
[context save:&error];

(I take my properties from a NSDictionary called dictionary)

(我从一个叫做dictionary的NSDictionary中获取属性)

To read your info:

阅读你的信息:

AppDelegate *appdelegate = [[UIApplication sharedApplication]delegate];
context = [appdelegate managedObjectContext];
NSEntityDescription *entitydesc = [NSEntityDescription entityForName:@"User" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entitydesc];

//NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NULL"];
[request setPredicate:nil];

NSError *error;
NSArray *matchingData = [context executeFetchRequest:request error:&error];
//NSArray *matchingData = [context executeFetchRequest:nil error:&error];

// If the user is not logged in previously
if (matchingData.count <=0 ){
    //self.displaylabel.text = @"No person find";
} else {
// If the user is already logged in
    for (NSManagedObject *obj in matchingData) {
        AppDataModel *appDataModel=[AppDataModel getInstance];
        appDataModel.appUserInfo = [User alloc]; 
        appDataModel.appUserInfo.name = [obj valueForKey:@"name"];
        appDataModel.appUserInfo.surname = [obj valueForKey:@"surname"];
    }
}

#5


2  

I know that this is not an answer to what the OP asked, but I wanted to share my experience about the same subject in case it will help someone else.

我知道这不是OP所要求的答案,但我想分享我对同一主题的经验,以防它对其他人有所帮助。

I had some issues with saving data persistently, anything seemed to help me fix it. The structure was very simple, an Entity with one field and one relationship (to-many). I made some changes to the class generated, NSMutableOrderedSet instead of NSOrderedSet.

我坚持不懈地保存数据,任何事情似乎都能帮我解决问题。结构非常简单,一个具有一个字段和一个关系(to-many)的实体。我对生成的类NSMutableOrderedSet做了一些更改,而不是NSOrderedSet。

I was not doing multi thread, or anything like that, just adding elements to the relationship. After saving, and re-launching the application, data just disappeared (elements added to the relationship).

我不是在做多线程,或者类似的东西,只是在关系中添加元素。保存并重新启动应用程序之后,数据就消失了(添加到关系中的元素)。

I ended up discovering that there is a property called updated. After adding the new element to the relationship, I checked if this property changed its value. It didn't. So I had to create another field in the Entity, a Boolean, just to be able to force the entity to be saved after adding elements to this relationship.

最后我发现有一个属性叫做update。在向关系中添加新元素之后,我检查这个属性是否改变了它的值。它没有。因此,我必须在实体中创建另一个字段,一个布尔值,这样就可以在添加元素后将实体保存起来。

entity.addObject(..)
entity.forceUpdate = true // without this line, it won't update
managedContext.save(..)

So I hope it helps anyone with the same problem, as I spent some time thinking that I was not saving it correctly..

所以我希望它能帮助有同样问题的人,因为我花了一些时间思考我没有正确地保存它。

#6


2  

Add this after you save your data :

保存数据后添加:

NSError *error = nil;
if (![managedObjectContext save:&error]) {
    NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}

#7


0  

After hours of debugging, I found that the reason my updates weren't being saved was because in my subclass of NSManagedObject I defined by properties w/ @synthesize instead of @dynamic.

经过数小时的调试,我发现之所以没有保存更新,是因为在NSManagedObject的子类中,我使用属性w/ @synthesize而不是@dynamic定义更新。

After I change it, it all saved as expected.

在我修改之后,它就像预期的那样被保存了下来。

Hope that helped someone.

希望帮助别人。