Using a single view for multiple NSManagedObjects
So I have a couple properties that are common across several of my Core Data entities. Notes, URL, etc.
I have a single view controller for editing this information, and I pass the Entity to it as a NSManagedObject
@property (nonatomic, retain) NSManagedObject *editedObject;
@property (nonatomic, retain) Thing *thing;
@property (nonatomic, assign, getter=isEditingThing) BOOL editingThing;
And to actually get the object in a state I could make changes I would
if([editedObject isKindOfClass:[Thing class]]) {
thing = (Thing *)editedObject;
editingThing = YES;
}
That way I can set the values on thing and save the managedObjectContext like normal.
However, this is crashin开发者_如何学Cg my application, but only if I enter and exit the View Controller for editing the field over and over again.
Which brings me to my question: What's the best way to handle using a single view controller to edit a common field on more than one Core Data Entity? Should I just set the Boolean and populate the correct entity property when I call the View Controller?
I imagine your thing
property is not getting retained because you're not using your accessor to set it. Change:
thing = (Thing *)editedObject;
to:
[self setThing:editedObject];
As to your bigger question, I think you need to provide more context. What do you mean by "edit a common field on more than one Core Data Entity"?
If both entities have a property called notes then change your property:
@property (nonatomic, retain) id managedObject;
Then when you go to set it, you can just set it without caring what the object is:
[[self managedObject] setNotes:...];
As long as whatever you set managedObject
to responds to the property notes
it will work just fine. If not, it will error out and you can test that easily.
You could go a more paranoid route and test if it responds first:
if ([[self managedObject] respondsToSelector:@selector(notes)]) {
but that is over protective since the only thing you would want to do that point is crash anyway.
精彩评论