Oh Danny Boy
Oh Danny Boy

Reputation: 4887

How to step inside NSManagedObject; access individual attributes

NSManagedObject *entryObj = [self.fetchedResultsController
                         objectAtIndexPath:indexPath];

entryObj consists of four String attributes.

If I NSLog entryObj, I get the information I want. I cannot figure out how to access each of these properties individually. I read a similar post where the solution was to call "entity." I cannot figure out how to use "entity" to access a specific attribute.

Any ideas? References? Tutorials?

Thanks in advance.

Upvotes: 2

Views: 2935

Answers (3)

For generating real classes with properties to call from your object model, I highly recommend using mogenerator:

http://github.com/rentzsch/mogenerator

That's the main project, but the easy to download installer is here:

http://rentzsch.github.com/mogenerator/

You also get primitive value accessors for numeric types, for free.

Upvotes: 0

Andiih
Andiih

Reputation: 12413

If you build your NSManaged objects with the designer then you can export model classes. From the xcdatamodel do File/New File then pick CocoaTouch Class/Managed Object Class. Next then Next then tick each of your classes. Leave generate accessors and generate obj-c 2.0 properties ticked and click finished.

Now you can include the generated files in your projects and use dot accessor syntax.

Alternatively use [entryObject valueForKey:@"keyname"]; but I prefer to stick to the dot accessor syntax where possible.

Upvotes: 0

Mike Weller
Mike Weller

Reputation: 45598

Properties on managed objects are KVC/KVO compliant so you can access them via:

[entryObj valueForKey:@"name"]

Alternatively you can generate a custom Core Data class with real properties to access these values. See this documentation for more information. The Xcode core data modelling tool can generate these classes for you. While you have the model open, choose "File->New File" and you should see a "Managed Object Class" item. Choose this and select the entities you wish to generate classes for.

Once you have done this and the core data entities have their class name set appropriately, you just cast the NSManagedObject to an instance of your new class and access its properties, i.e.

MyObject *entryObj = (MyObject *) [self.fetchedResultsController
    objectAtIndexPath:indexPath];
NSLog(@"Property is %@", entryObj.whatever);

Upvotes: 5

Related Questions