您不一定需要与AppDelegate
通信,但您可以通过[[UIApplication sharedApplication] delegate]
。然后,您可以访问你需要什么都特性,但你会probabaly需要转换它:
// assuming your application delegate is of type 'AppDelegate' - usually the default provided by Xcode
AppDelegate *delegate = (AppDelegate*)[[UIApplication shared application] delegate];
// you can now all you application delegat's properties.
另一种方法,在你的Cat
类,是为notifications posted by the app delegate注册。例如:
@implementation Cat
-(id)init {
if ((self = [super init])) {
// you can also attempt to read stored values form disk here
// perform all your other initialization that you already have
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleNotification:)
name:UIApplicationDidEnterBackgroundNotification
obect:[UIApplication sharedApplication];
}
}
在你Cat
类,定义了一个方法handleNotification:
,因为这是提供给通知中心选择器。这是该方法时UIApplicationDidEnterBackgroundNotification
张贴通知中心将在您的Cat
类致电:
-(void)handleNotification:(NSNotification*)notification {
NSString *name = notification.name;
id sender = notification.object;
if ([name isEqual:UIApplicationDidEnterBackgroundNotification] && [sender isEqual:[UIApplication sharedApplication]) {
// save `Cat` class to disk as plist or however you want
}
}
你也可以用UIApplicationWillResignActiveNotification
替代UIApplicationDidEnterBackgroundNotification
。我会把它留给你决定哪个最适合你的需求。
More on using the NSNotificationCenter
。
UPDATE:
第二种方法的优点是没有必要为您的Cat
类和应用程序代理之间的任何specfic知识或扶养。两个对象都可以独立运行。 [UIApplication sharedApplication]
是可用于在iOS应用程序中运行的任何对象的单例,但您不需要知道确切的类型。所需的唯一具体知识是通知名称,但即使是全球通用名称也是如此。
发布代码是获得帮助的最佳方式之一。一些提示,如果您知道具体方法中的问题,请发布该方法,并使用**相关**错误消息。如果我们需要更多,我们会让你知道。 – 2013-03-03 21:40:16
如果我理解正确,你想在应用程序进入后台时保存你的Cat类。 – 2013-03-03 21:42:09
@MikeD嗯我真的没有理解你,但如果你想在这里的代码,我可以发布它,这不是一个问题,如果你对我的问题有问题,我准备回答所有的问题:) – 2013-03-03 21:43:32