Question

I have an iPad app using Core Data. In my data model I have an object called HubBrand and have generated NSManagedObects using XCode. The generated object has the following code:

Header:

@class HubModel;

@interface HubBrand : NSManagedObject

@property (nonatomic, retain) NSString * brandName;
@property (nonatomic, retain) NSSet *relModels;
@end

@interface HubBrand (CoreDataGeneratedAccessors)

- (void)addRelModelsObject:(HubModel *)value;
- (void)removeRelModelsObject:(HubModel *)value;
- (void)addRelModels:(NSSet *)values;
- (void)removeRelModels:(NSSet *)values;

@end

Implementation:

@implementation HubBrand

@dynamic brandName;
@dynamic relModels;

@end

I am trying to create an instance of the HubBrand class and populate it using the foloowing code:

HubBrand *brand = [[HubBrand alloc] init];
[brand setBrandName:[NSString stringWithFormat:@"_Custom:, %@", [_txtHubBrand text]]];
//brand.brandName = [NSString stringWithFormat:@"_Custom:, %@", [_txtHubBrand text]];

When I do so, I get the following runtime error: -[HubBrand setBrandName:]: unrecognized selector sent to instance

When using generated managed objects, am I required to implement my own setters? Any clues as to why I am getting this error? Thanks!

Was it helpful?

Solution

You need to create an instance of a sub class of a NSManagedObject using a NSManagedObjectContext based on its NSEntityDescription:

NSManagedObjectContext *managedObjectContext; // Get this from your Core Data stack, probably in the app delegate
HubBrand *brand = [NSEntityDescription insertNewObjectForEntityForName:@"HubBrand" inManagedObjectContext:managedObjectContext];
[brand setBrandName:[NSString stringWithFormat:@"_Custom:, %@", [_txtHubBrand text]]];

See the Creating, Initializing, and Saving a Managed Object section of the doc for more info.

You can also use the sub classes initializer:

NSEntityDescription *entity = [NSEntityDescription entityForName:@"HubBrand" inManagedObjectContext:managedObjectContext];
HubBrand *brand = [[HubBrand alloc] initWithEntity:entity insertIntoManagedObjectContext:managedObjectContext];

But its a bit more wordy!

OTHER TIPS

You're not calling the designated initializer for NSManagedObject, so you're not getting valid objects. You can't create instances using init, you have to use initWithEntity:insertIntoManagedObjectContext:. It's also possible to use the constructor on NSEntityDescription called insertNewObjectForEntityForName:inManagedObjectContext:.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top