开发者

CoreData (storing new object) in AppDelegate = SIGABRT

开发者 https://www.devze.com 2023-04-07 15:45 出处:网络
I\'ve intented to make a simple function in AppDelegate to store some data in 开发者_如何转开发database (CoreData) which would be called from various ViewController classes connected do AppDelegate. T

I've intented to make a simple function in AppDelegate to store some data in 开发者_如何转开发database (CoreData) which would be called from various ViewController classes connected do AppDelegate. This is the body of this function:

- (void) setSetting:(NSString *)setting :(NSString *)value {    
    NSManagedObject* newSetting = [NSEntityDescription insertNewObjectForEntityForName:@"EntityName" inManagedObjectContext:self.managedObjectContext];
    [newSetting setValue:value forKey:setting];
    NSError* error;
    [self.managedObjectContext save:&error];
}

But calling this function (even from AppDelegate itself) returns SIGABRT on line with setValue

But when I implement the function in ViewController class (replacing self. with proper connection to AppDelegate of course) - it works fine.

I don't get it and I would really appreciate some help in creating flexible function in AppDelegate to save the data in database.


This looks a bit like the key part is not an NSString or the value part is not the correct data type. Please check, and perhaps make the order of the arguments in your function the same as in the setValue:forKey method to avoid confusion.

Also, according to the documentation, an exception will be raised if the key is not defined in the model - so double-check your key strings.

BTW, if this is your error it is a good idea to move away from KVC and create your own NSManagedObject subclasses instead as a habit - makes life much easier.


The most likely explanation is that this line:

NSManagedObject* newSetting = [NSEntityDescription insertNewObjectForEntityForName:@"EntityName" inManagedObjectContext:self.managedObjectContext];

… returns a nil object either because the entity name is incorrect or because the managedObjectContext is itself nil or otherwise invalid.

Since the problem only occurs in the app delegate, I would first suspect some issue with self.managedObjectContext.

0

精彩评论

暂无评论...
验证码 换一张
取 消