【发布时间】:2015-04-20 09:08:03
【问题描述】:
我正在尝试在应用退出时调用 removeObserver()。但是当我使用 NSLog() 进行检查时,我发现在 iOS 模拟器中应用退出后,既没有调用 viewWillDisappear() 也没有调用 viewDidDisappear() .在类似问题中,我使用的是单一视图模板,而不是导航控制器。
这里是源代码:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"viewDidLoad() called");
// Do any additional setup after loading the view, typically from a nib.
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
for (int i = 0; i < 4; i++) {
UITextField *theField = self.lineFields[i];
theField.text = array[i];
}
}
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationWillResignActive:)
name:UIApplicationWillResignActiveNotification
object:app];
}
- (void)viewWillDisappear:(BOOL)animated {
NSLog(@"viewWillDisappear() called");
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = paths[0];
return [documentDirectory stringByAppendingPathComponent:@"data.plist"];
}
- (void)applicationWillResignActive:(NSNotification *)notification {
NSString *filePath = [self dataFilePath];
NSArray *array = [self.lineFields valueForKey:@"text"];
[array writeToFile:filePath atomically:YES];
}
@end
【问题讨论】:
-
你是关闭还是杀掉应用程序?
-
我试过两种方法: 1、双击home键,关闭app; 2.我直接退出了iOS模拟器。在这两种情况下,都不会调用任何方法。
-
在应用委托中使用 applicationWillTerminate:。
-
什么是部署目标?因为如果它小于 7.0,那么当您终止应用程序时不会调用 applicationWillTerminate。
-
@aBilal17 谢谢。如何在应用委托中引用视图控制器?
标签: ios objective-c xcode viewwillappear