Saving and Deleting NSManagedObject & NSManagedObjectContext

匆匆过客 提交于 2019-12-06 03:00:51
  1. To delete you just need to delete letsMeet object from NSManagedObjectContext.

    NSError *error;
    [managedObjectContext deleteObject:letsMeet];
    [managedObjectContext save:&error];

Since you always have only one object, getting the reference of letsMeet is not a problem. You can do as you did in your code.
Update: And you don't need to delete the managed object context. It just a space to deal with your objects. More explanation at the end of question.

2. If the LetsMeet entity is modeled in a way that all the form elements are attributes of LetsMeet, when you save the managedObjectContext after creating a LetsMeet object as you have done in code, this will be saved as a single object.

3.You already know how to retrieve an object as thats what you are doing in the code. Everything becomes easy as you are only using one object. In the case of multiple objects to get a the unique object, you should either implement a primary key,(maybe formID, i.e; add another attribute to LetsMeet) or you should know what the objectId of each object is and then set the predicate of your fetch request accordingly.

NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:letsMeet];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"formId like %@", formId];
[request setPredicate:predicate];

NSArray *resultsArray =[managedObjectContext executeFetchRequest:request error:&error];

If your formId is unique, this will return you a single object array.

But if you are using core-data for only handling one object, you could've used NSUserDefaults or write to a plist File to do this. This is kind of overkill.

Update: To get the objectId of a NSManagedObject:

 [letsMeet objectId];

ManagedObjectContext is like a whiteboard. The object you have inside the array, the object inside managed object context, its all the same. You can change the objects, add object, delete object etc. Only thing is whatever is the current state of the object(s) when you do a [managedObjectContext save:] , that is written to disk.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!