applicationWillResignActive在设备上未被捕获的通知

时间:2011-10-13 16:04:13

标签: objective-c ios nsnotifications

我正在尝试在应用程序关闭时在简单的.plist文件上保存一个简单的字符串。

这是我的代码:

- (void)viewDidLoad {
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
    NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
    self.kmOld.text = [array objectAtIndex:0];

    [array release];
}


[[NSNotificationCenter defaultCenter] addObserver:self
                                      selector:@selector(applicationWillResignActive:)
                                      name:UIApplicationWillResignActiveNotification 
                                      object:NULL];
[super viewDidLoad];

}

然后按照applicationWillResignActive方法执行:

 - (void)applicationWillResignActive:(NSNotification *)notification {

    NSString *text = [[NSString alloc]initWithFormat:@"%@",kmNew.text];
    NSLog(@"%@",text);

    if ([text intValue]>0) {
        NSArray *array = [[NSArray alloc] initWithObjects:text, nil];

      BOOL success = [array writeToFile:[self dataFilePath] atomically:YES];
        NSLog(@"%d",success);
        [array release];
    }
    [text release];
}

这在模拟器上工作正常,但它似乎被设备忽略了...... 问题出在哪儿?感谢...

1 个答案:

答案 0 :(得分:8)

查看http://www.cocoanetics.com/2010/07/understanding-ios-4-backgrounding-and-delegate-messaging/,了解UIApplication生命周期的概况。根据您的应用运行的iOS版本以及导致您的应用终止/后台的操作,您可能没有收听正确的通知,也可能需要观察UIApplicationWillTerminateNotification。

iOS <4

iOS 4+