Creating a Instance Variable using Core Data and Magical Record

限于喜欢 提交于 2019-12-12 02:34:50

问题


Currently in a given method within a given class I can create a instance of a custom variable managed by Core Data and Magical Record with the following line

AViewController.m

List *list = [List MR_createInContext:_managedObjectContext];

I can then set the list's properties like so:

list.name = @"FooBar Name";

My question: In AViewController.h can I do the following -

@interface AViewController : UIViewController {
    /* Define Local List Var for AViewController class */
    List *list;
}

Then in .m

viewdidload {
list = [List MR_createInContext:_managedObjectContext];
}

someCustomMethod {
  list.name = @"FooBar Name";

  [_managedObjectContext MR_save];
}

回答1:


Your code should work. But if you are trying to create new objects from input elements (maybe on button click), new objects will be created only by running the application again and again. What I mean is if your someCustomMethod is called again and again the same object will get rewritten with the values. (Which is fine if that is what you want.)

But if you want to create new objects you should initialize it again inside the object. i.e. you should use the below code:

viewdidload {
list = [List MR_createInContext:_managedObjectContext];
}

someCustomMethod {
  list.name = @"FooBar Name";

  [_managedObjectContext MR_save];

  list = [List MR_createInContext:_managedObjectContext]; //add this line

}

So this way old object will be saved and new object will be created each time someCustomMethod is called.




回答2:


This pattern is very common and the code you posted should work.

I don't exactly know how MR works, but in Cord Data you would have to delete the object from the context if you want to discard it, otherwise it will be saved with the next save.



来源:https://stackoverflow.com/questions/17801775/creating-a-instance-variable-using-core-data-and-magical-record

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