app crashes when releasing appDelegate instance
i have this code that passes the core data context to one of the controllers. it was working great for few days, until the debugger started to give me the "not A type release" error and crashing the app. i have checked t开发者_运维百科he app for leaks and i found leaks from the SappDelegate object. so i understand that i have to release it but it keeping crashing every time i do it.
any ideas thanks shani
SAppDelegate *hbad= [[SAppDelegate alloc] init];
NSManagedObjectContext *context = [hbad managedObjectContext];
[hbad release];
if (!context) {
NSLog(@"problem with mannaged");
}
self.managedObjectContext = context;
If SAppDelegate is your actual app delegate, that is not the correct way to get it. you should change your code to:
SAppDelegate *hbad= [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [hbad managedObjectContext];
if (!context) {
NSLog(@"problem with mannaged");
}
self.managedObjectContext = context;
Also, leaks will not cause crashes until MUCH later when your application runs out of memory and the system kills it.
I'm not entirely sure why you're creating a new SAppDelegate. You should only have one of these and it gets created for you on startup. Why do you need another SAppDelegate instance?
You should see Elfred's answer to get the app delegate instead of creating one.
However, there is one bug in the code you have posted . . .
You need to retain the context until you're done with it. Either :
SAppDelegate *hbad= [[SAppDelegate alloc] init];
NSManagedObjectContext *context = [[hbad managedObjectContext] retain];
[hbad release];
if (!context) {
NSLog(@"problem with mannaged");
}
self.managedObjectContext = context;
[context release];
or release hbad later on :
SAppDelegate *hbad= [[SAppDelegate alloc] init];
NSManagedObjectContext *context = [hbad managedObjectContext];
if (!context) {
NSLog(@"problem with mannaged");
}
self.managedObjectContext = context;
[hbad release];
精彩评论