简体   繁体   中英

Crash when manipulating a simple Core Data object

I'm diving into iOS development and I have a few questions about manipulating a simple Core Data object that I created in Xcode. After using the object editor, here's the class that Xcode generated for me...

@interface Alarm :  NSManagedObject  
{
}

@property (nonatomic, retain) NSNumber * Enabled;
@property (nonatomic, retain) NSString * Label;
@property (nonatomic, retain) NSNumber * Snooze;

@end

@implementation Alarm 

@dynamic Enabled;
@dynamic Label;
@dynamic Snooze;

@end

Here's a code snipped where I try and create an Alarm object that I plan to add to my ManagedObjectContext...

- (void)saveAlarm:(id)sender {

    Alarm *alarm = [[Alarm alloc] init];

    alarm.Label = [NSString stringWithString:txtLabel.text];    
    alarm.Snooze = [NSNumber numberWithBool:switchSnooze.on];
    alarm.Enabled = [NSNumber numberWithBool:YES];

    [addAlarmDelegate insertNewAlarm:alarm];
    [alarm release]; 
}

My code crashes the first time I try and assign a value to one of the properties of alarm, on the line...

alarm.Label = [NSString stringWithString:txtLabel.text];

with the following crash message in the console...

reason: '-[Alarm setLabel:]: unrecognized selector sent to instance 0x5e33640

what am I missing here?

Thanks so much in advance for your help!

I would look into using mogenerator:

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

The command line to run it is:

mogenerator -m MyAwesomeApp.xcdatamodel -O Classes

Whatever directory you put after -O is where the produced classes go. The great thing is it has simpler methods to create new manage objects in a context, and also produces a class you can customize (adding your own methods) that do not get removed even when you regenerate objects from your model.

Much simpler than using the XCode object generation.

You should not allocate and init an NSManagedObject-based object directly. You should use

[NSEntityDescription insertNewObjectForEntityForName:@"Alarm" inManagedObjectContext:moc];

It might be the reason for it not to work. Because it is usually pretty straight forward to make it work.

The documentation says:

If you instantiate a managed object directly, you must call the designated initializer (initWithEntity:insertIntoManagedObjectContext:).

And in initWithEntity:insertIntoManagedObjectContext:'s documentation:

Important: This method is the designated initializer for NSManagedObject. You must not initialize a managed object simply by sending it init.

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