我有一个名为 ContentController 的类。我从 ViewController 创建它的实例。第一个家伙从我的远程服务器获取一些数据,在上面做一些事情。然后它将信息传递给 ViewController,向用户展示一些好的东西。到现在为止还挺好。
现在,问题出在使用 AppDelegate 时。当应用程序尝试进入后台模式时,我想访问同一个实例(ContentController)。并在设备上保存一些属性。这是行不通的。
你能帮帮我吗?
我有一个名为 ContentController 的类。我从 ViewController 创建它的实例。第一个家伙从我的远程服务器获取一些数据,在上面做一些事情。然后它将信息传递给 ViewController,向用户展示一些好的东西。到现在为止还挺好。
现在,问题出在使用 AppDelegate 时。当应用程序尝试进入后台模式时,我想访问同一个实例(ContentController)。并在设备上保存一些属性。这是行不通的。
你能帮帮我吗?
如果您真的想从 AppDelegate 访问 ContentController 实例,您可以在 AppDelegate 中创建一个属性。
//AppDelegate.h
@property (strong, nonatomic) ContentController *contentController;
当您需要在 ViewController 中使用它时,您可以使用,
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
appDelegate.contentController = [[ContentController alloc] init];
或者您可以在我们的 ViewController 类中创建一个指向 AppDelegate 实例的属性。
self.contentController = appDelegate.contentController;
从您的 ContentController 注册通知。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
并在 Content 控制器中实现一个applicationWillResignActive:
方法来做任何你想做的事情。
- (void)applicationWillResignActive:(NSNotification *)notification
{
// Your server calls
}
要在 applicationDidEnterBackground 上保存属性值:您可以在类的 viewDidLoad 方法中添加一个通知观察者,如下所示:
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
在 viewDidUnload 你应该添加这个:
[[NSNotificationCenter defaultCenter] removeObserver:self];
还将这两种方法添加到您的类 .m 文件中(您可以在下面看到我的一个应用程序中的示例):
- (void)applicationWillResignActive:(NSNotification *)notification {
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:[NSNumber numberWithInt:self.event.eventID]];
[array addObject:self.event.eventName];
[array addObject:[NSNumber numberWithDouble:[self.event.ticketPrice doubleValue]]];
[array writeToFile:[self dataFilePath] atomically:YES];
[array release];
}
此方法将从您的文件中加载数据,在您的 viewDidLoad 中调用:
- (void)loadEventFromEventPlist {
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
self.event.eventID = [[array objectAtIndex:0] intValue];
self.event.eventName = [array objectAtIndex:1];
self.event.ticketPrice = [NSNumber numberWithDouble:[[array objectAtIndex:2] doubleValue]];
[array release];
}
}
获取文件名需要此方法:
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
}