vikmalhotra
vikmalhotra

Reputation: 10071

iPhone: Cannot access NSManagedObjectContext using appDelegate

I have started with iPhone development sometime back and I am trying to implement core data in my application.

In the process of executing FetchRequest I am stuck at following code...

MYAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];

While debugging the following error is displayed...

Program received signal: "EXC_BAD_ACCESS"

When I run the app, it just crashes.

This error appears again and again when I press 'continue' button in debug mode.

I tried changing my code, to this.....

NSManagedObjectContext *context = [(MyAppDelegate *)[[UIApplication sharedApplication\ delegate] managedObjectContext];

This lets the app run but when I press the Simulator home button, the same error is displayed in console.

What could be going wrong over here?

Upvotes: 2

Views: 1679

Answers (1)

Jeremy Massel
Jeremy Massel

Reputation: 2267

Make sure you have a public accessor method for your application delegate. I would implement it like so, at the top of your AppDelegate.m


+ (MYAppDelegate *)sharedAppDelegate
{
    return (MYAppDelegate *) [UIApplication sharedApplication].delegate;
}

You may then access it using:


[[MYAppDelegate sharedAppDelegate] managedObjectContext]

Upvotes: 2

Related Questions