问题
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