开发者

Core Data Relationship Failing to Load To-One Relationship

开发者 https://www.devze.com 2023-01-13 04:53 出处:网络
I have a to-one relationship between a Document and Settings model: On creation of a Document, a corresponding Settings object is created. The models are persisted to core data.

I have a to-one relationship between a Document and Settings model:

Core Data Relationship Failing to Load To-One Relationship

On creation of a Document, a corresponding Settings object is created. The models are persisted to core data.

When relaunching after creating a few documents (and the associate settings), the application reloads a list of documents to select using:

// Load delegate from shared application and context from delegate.
SampleAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = delegate.managedObjectContext;

// Create new request.
NSFetchRequest *request = [[NSFetchRequest alloc] init];

// Create entity description using delegate object context.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Document" inManagedObjectContext:context];

// Set entity for request.
[request setEntity:entity];

// Load array of documents.
NSError *error;
NSArray *documents = [context executeFetchRequest:request error:&error];

// Rlease des开发者_StackOverflow中文版criptor.
[descriptor release];

// Release request.
[request release];

// Done.
return documents;

The list appears fine (the documents are loading). However, when attempting to access the settings for any of the documents the program exits giving:

Program received signal: “SIGABRT”.

The modifications to the settings are triggered when a user selects a button. Strangely enough, the program does not crash if the following snippet is added just before returning the documents on load (i.e. if the relationships are accessed while loading):

for (Document *document in documents)
{
    NSLog(@"document.name: %@", document.name);
    NSLog(@"document.settings.stroke: %@", document.settings.stroke);
    NSLog(@"document.settings.stroke: %@", document.settings.stroke);
}

The property for the relationship is "(nonatomic, retain)" and uses "@dynamic". Any ideas? Thanks!


In your Core Data model, did you set up an inverse relationship between Document & Settings? If not, you must.


After spending way too much time on this bug, I finally figured it out. During the initial load of the values, I setting a KVO. This code was causing crashes the crashes (although they were not appearing until the next run loop):

[self.document.settings addObserver:self forKeyPath:@"fill" options:0 context:NULL];
[self.document.settings addObserver:self forKeyPath:@"stroke" options:0 context:NULL];

Not sure why it was an issue, but I was lucky enough to be able to simply remove it for now.

0

精彩评论

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

关注公众号