質問

I'm using MagicalRecord throughout my iPad app; I have a line of code, that intermittently throws an exception:

+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name...

which I understand is because the NSManagedObjectContext is nil. The app runs for quite a while until the error is triggered by this line of code and others similiar to it (using different entities):

    [apptDataArray addObjectsFromArray:[AppointmentInfo MR_findAllWithPredicate:predicate]];

The NSManagedObjectContext is defined in AppDelegate.h as

NSManagedObjectContext *defaultContext;

and further in AppDelegate.m as

    defaultContext = [NSManagedObjectContext MR_defaultContext]; 

where it is used throughout the app. In a different SO question I had asked, Saul Mora said this:

By creating a new context every time you save, and not re-using the context, you will guarantee to not cross threads, and to not crash your app 1% of the time.

Could it be that my saves are somehow destroying the defaultContext object? If so, would it be wise of me to create a new defaultContext for each MR method call?

役に立ちましたか?

解決

and further in AppDelegate.m as

defaultContext = [NSManagedObjectContext MR_defaultContext]; 

... this is likely AOK, since you are likely on the main thread.

where it is used throughout the app.

... this is less OK, since "throughout the app" implies that are you possibly on not the main thread.

You probably want to use [NSManagedObjectContext MR_contextForCurrentThread] in specific places.

Take a look at what [NSManagedObjectContext MR_defaultContext] and [NSManagedObjectContext MR_contextForCurrentThread] do in MagicalRecord (type that out in your code, and cmd-click on it for a fast way to find it). You'll see that MR_contextForCurrentThread uses the defaultContext on the main thread, and creates a new context parented to the defaultContext on other threads.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top