Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add attributes to a core data class created with the data model?

I'm creating a todo app:

I created an entity in my projects .datamodel file, I added the entity an attribute of a string called "content" and created NSManagedObject subclass with the "editor" > "Create NSManagedObject subclass:

enter image description here

This class was created:

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>


@interface Targets : NSManagedObject

@property (nonatomic, retain) NSString * content;

@end

but now I want another "id" attribute to do I can give each todo an id... How should I do this? is it ok to do it manually? since I generated it from the entity model it feels like I need to create a new entity to do that...?

If you can direct me, and maybe through an explanation how that works it would be awesome..maybe I dont understand something here and this is why I'm asking this question

like image 564
JohnBigs Avatar asked Mar 18 '23 21:03

JohnBigs


2 Answers

In light of the fact that Xcode appears to have a bug which prevents it from appropriately replacing your CoreData files, I've rewritten my answer with a workaround.

  1. Delete the originally generated class file:

enter image description here

(Click move to trash.)

  1. Add the attribute:

enter image description here

  1. Generate the class in the exact manner you generated the original we deleted in step 1: enter image description here
like image 151
nhgrif Avatar answered Mar 20 '23 11:03

nhgrif


So, the solution to your problem is actually quite simple:

To add another attribute to your entity, you can just approach it exactly in the same way as you did with the content attribute. Just add the attribute within the graphical editor, just like you did before with content, and then again, use Xcode's built-in functionality to generate the classes, in the same way as you did before.

What will happen is that Xcode overrides the formerly generated files, and replaces them with a new version that now has the attributes. There is no harm in doing that process as often as you like. :)

EDIT: Short side note, you need to remember to delete the app from your device (or the simulator) after you changed the data model, because otherwise the app will crash because your new Core Data model is not consistent with the one you used before. Second, if you want to add functionality to your data model classes (which you should do with much care anyway, but maybe some utility Core Data functions or so...), you should make use of iOS categories, so that the code which you wrote for that doesn't get deleted when you regenerate your model classes. The Stanford Lecture on iOS development has a great introduction session on Core Data where this approach is explained in detail!

like image 27
nburk Avatar answered Mar 20 '23 11:03

nburk