I have this object:
@interface Song : NSManagedObject
@property (nonatomic, strong) NSString *songName;
@property (nonatomic) int32_t achievedPoints;
When I set the properties like this
Song *song1 = [[SongStore sharedStore] createSong];
song1.songName = @"Song 1";
song1.achievedPoints = 0;
everything works, however once I try to set the achievedPoints
variable to something else than 0 I get an EXC_BAD_ACCESS.
This is what the createSong
method does:
- (Song *)createSong {
double order;
if ([allSongs count] == 0) {
order = 1.0;
} else {
order = [[allSongs lastObject] orderingValue] + 1.0;
}
Song *p = [NSEntityDescription insertNewObjectForEntityForName:@"Song" inManagedObjectContext:context];
[p setOrderingValue:order];
[allSongs addObject:p];
return p;
}
I have no idea why getting the value and setting it to 0 works but anything else than zero crashes the program. Any help is highly appreciated.
This has happened to me once before. I don't know exactly which settings gets messed up, but there is a setting in your managed object model, I think, that controls whether or not the class should use primitive values (int, float, etc) or object values (NSNumber *, etc) to set its values. If this gets messed up, and you think you are setting a primitive when you are actually setting an object the following will happen:
//song1.achievedPoints = 0;
song1.achievedPoints = (NSNumber *)0x00000000;
//This is OK because it is the same as nil
//song1.achievedPoints = 1;
song1.achievedPoints = (NSNumber *)0x00000001; //You can see why this is bad!
My solution was to regenerate the class via the Create NSManagedObject Subclass template, making sure that Use Scalar Values for Primitives was checked.
This issue happened to me because the entity wasn't correctly linked to my class files. When this happened, Core Data creates its own subclass dynamically, rather than using my own, and that subclass's setters expect boxed primitives.
You can fix this by ensuring the "Class" property of your entity in the model file is set to the correct class, and not the default NSManagedObject
.
When you use XCode's Create NSManagedObject Subclass template, XCode will automatically set this value for the corresponding entity in the model file. This is probably what fixed borrrden's problem. However, you should be able to achieve the same result without creating new files by ensuring this value is set correctly.
来源:https://stackoverflow.com/questions/15001656/exc-bad-access-when-setting-integer-to-anything-else-than-zero