0

When I create an entity using core data then generate a subclass of NSManagedObject from it I get the following output (in the .h):

@class Foo;

@interface Foo : NSManagedObject

@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSSet *otherValues;

@end

However, in my .m file I want to make use of the name and otherValues values. Normally I would simply create a couple of ivars and then add the properties for them as I required. That way I can access them in my .m file easily.

In this situation would it be acceptable to do this? Would adding ivars to the .h (for name and otherValues) cause any unusual behaviour in the persistance & retrieval of objects?

1 Answers1

5

You don't use instance variable to access attributes of Core Data managed objects.

The generated implementation file contains the statements

@dynamic name;
@dynamic otherValues;

which means that the getter/setter functions for the Core Data properties are created dynamically, e.g. to retrieve the value from the managed object context or from the underlying persistent store.

So you should always use the properties to access the attributes, for example:

Foo *myFoo = [NSEntityDescription insertNewObjectForEntityForName:@"Foo" inManagedObjectContext:context];
myFoo.name = @"test";

Alternatively, you can use the key-value methods:

[myFoo setValue:@"test" forKey:@"name"];

See also: Modeled Properties in the "Core Data Programming Guide":

Core Data dynamically generates efficient public and primitive get and set attribute accessor methods ... In a managed object sub-class, you can declare the properties for modeled attributes in the interface file, but you don’t declare instance variables.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Another read worthy part of the Core Data documentation is [Managed Object Accessor Methods](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdAccessorMethods.html). Especially if you are interested in custom getters and setters – Matthias Bauch Nov 19 '12 at 11:09
  • 1
    @downvoter: If you would leave a comment, then I could try to fix or improve my answer. I have no problems to admit an error, or to delete my answer in favor of a better one. – Martin R Nov 19 '12 at 12:06
  • Thanks very much for this answer - it has really helped me understand the use of NSManagedObjects. –  Nov 19 '12 at 12:29