简体   繁体   中英

Adding ivars to NSManagedObject subclass

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?

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, eg 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM