Search code examples
objective-ccore-dataexc-bad-accessnsnumber

Trying to access Core Data Model's NSNumber property gives EXC_BAD_ACCESS


I have an entity called Weather in my Core Data in the following form:

xcdatamodel

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@interface WeatherModel : NSManagedObject

@property (nonatomic, retain) NSString * cityName;
@property (nonatomic, retain) NSNumber * latitude;
@property (nonatomic, retain) NSNumber * longitude;
@property (nonatomic, retain) NSNumber * temperature;
@property (nonatomic, retain) NSNumber * humidity;
@property (nonatomic, retain) NSNumber * windSpeed;
@property (nonatomic, retain) NSNumber * rain;
@property (nonatomic, retain) NSDate * date;
@property (nonatomic, retain) NSString * iconId;
@property (nonatomic, retain) NSString * units;

@end

I save the instances of this model to Core Data as follows:

WeatherModel *bookmarkWeatherModel = (WeatherModel*)[DatabaseHelper insertNewEntityWithName:@"Weather" andContext:self.weatherManagedObjectContext];

[bookmarkWeatherModel setLatitude:[NSNumber numberWithDouble:0.0]];
[bookmarkWeatherModel setLongitude:[NSNumber numberWithDouble:0.0]];
[bookmarkWeatherModel setCityName:@"CityA"];
NSLog(@"%@", bookmarkWeatherModel.cityName);
NSLog(@"%@", bookmarkWeatherModel.latitude);

[DatabaseHelper saveCoreData:self.weatherManagedObjectContext];

However whenever I try to access any of the NSNumber properties (even after calling saveCoreData method), I get this error.

insertNewEntityWithName method in DatabaseHelper:

+ (NSManagedObject *)insertNewEntityWithName:(NSString *)entityName
                                  andContext:(NSManagedObjectContext *)managedObjectContext {
    NSManagedObject *entity = [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:managedObjectContext];
    return entity;
}

I tried accessing every single property in my model and only properties that throw this error are of type NSNumber. The others work just fine.


Solution

  • Apparently the problem was that I wrote the code for the model by hand. I solved the problem by generating the code automatically. I did that by choosing my entity in xcdatamodel, filling in the Class Name(WeatherModel) and Codegen(Manual/None) in data model inspector and then choosing Editor>Create NSManagedObject Subclass.