Zhu*_*gqi 2 xcode objective-c viewwillappear ios
我试图在应用程序退出时调用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
Run Code Online (Sandbox Code Playgroud)
我建议您添加应用程序更改的侦听器:
- (void)registerNotifications {
// Add observers to application state changes
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(applicationDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(applicationDidBecomeActive:)
name:UIApplicationDidBecomeActiveNotification
object:nil];
}
Run Code Online (Sandbox Code Playgroud)