开发者

EXEC_BAD_ACCESS on applicationWillEnterForeground in iOS3 but not iOS4

I have my application working great on my iOS 4.3.3 iPhone 3GS. When I test the app on a 3.1.3 iPhone 3G, the program crashes 开发者_开发知识库right after the splash image is shown. The debugger points to the last command of my root view controller's awakeFromNib:

- (void)awakeFromNib
{
    NSLog(@"awakeFromNib");
    NSLog(@"applicationWillEnterForeground listened");
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(applicationWillEnterForeground:)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object: nil];
}

.

2011-08-09 15:56:24.585 AppName[4401:207] awakeFromNib
2011-08-09 15:56:24.602 AppName[4401:207] applicationWillEnterForeground listened
Program received signal:  “EXC_BAD_ACCESS”.

Is there something special about iOS 3's awaking/sleeping that I should know that would help me work around this problem?


From the iOS Developer library:

UIApplicationWillEnterForegroundNotification

Posted shortly before an application leaves the background state on its way to becoming the active application. The object of the notification is the UIApplication object. There is no userInfo dictionary.

Availability

Available in iOS 4.0 and later.

This probably causes the EXEC_BAD_ACCESS. Does it crash if you remove that line of code?


The problem is that the identifier UIApplicationWillEnterForegroundNotification is pointing to an externally defined string that only exists on iOS 4 or later. On iOS 3 and earlier, it will evaluate to nil; thus, you are passing in nil for a notification name, which is why adding the observer is crashing.

You can fix this in two ways. You could directly use the string value of the notification's name in your code:

[[NSNotificationCenter defaultCenter]
 addObserver:self 
 selector:@selector(applicationWillEnterForeground:)
 name:@"UIApplicationWillEnterForeground" // might not be correct
 object:nil];

I'm not sure if that's what it is, you'll have to check the docs or use NSLog to be exactly sure of it.

A better option is to check the value of the identifier first, and only add a listener if it is supported:

if (UIApplicationWillEnterForegroundNotification) {
    [[NSNotificationCenter defaultCenter]
     addObserver:self 
     selector:@selector(applicationWillEnterForeground:)
     name:UIApplicationWillEnterForegroundNotification
     object:nil];
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜