这是一个陈腐的问题,我有一些编程经验,但Objective-c对我来说是全新的,我无法找到关于整个objective-c概念的任何明确的定义。这里有一些我已经知道的理论:我无法直接访问类的实例变量,因此我必须使用属性或“访问器方法”来访问它。好的。我尝试了一些我的意思是存取方法,但嗯,这都是错的。我想你可以帮我解决这个问题。
这是我的例子: 我有班级猫,还有一个关于猫的信息。 Plist存储宠物的名称和年龄。我想这样做:具有textField,label和按钮的简单视图。标签 - 是当前的宠物名称,textField用于更改现在的文本字段方法中的猫名称(更改猫名称听起来令人毛骨悚然,但这只是一个示例),以及一个向更改名称功能发送消息的按钮。在我按下主页按钮后,我想通过AppDelegate.m文件将名称保存到文件中,这是一个问题,我将在下面介绍。
我不知道如何将代码打包到一个隐藏的块中,直到你打开它为止,所以我不想在这里用大量的代码行来打扰你的眼睛。我添加了代码的链接和一些带日志输出的屏幕。 (如果有人会说我怎么做,我会在这里添加代码),但现在这里是链接: http://shlonger.com/680dc6cf21aa426c4bed107213ab4467
我无法从AppDelegate访问应用程序运行时实现的对象。我为类变量创建了一些属性和一些getter / setter方法,但是当我在AppDelegate中初始化Cat类时,它只使用默认的另一个对象(如在plist文件中)设置。如何以正确的方式通过AppDelegate保存当前设置?
很抱歉有很长的问题说明。
答案 0 :(得分:3)
您不一定需要与AppDelegate
进行通信,但可以通过[[UIApplication sharedApplication] delegate]
进行通信。然后,您可以访问所需的任何属性,但您可能需要进行投射:
// 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:
,因为这是提供给通知中心的选择器。这是发布Cat
时通知中心将在UIApplicationDidEnterBackgroundNotification
课程中调用的方法:
-(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
}
}
您也可以将UIApplicationDidEnterBackgroundNotification
替换为UIApplicationWillResignActiveNotification
。我将把它留给你决定哪种最适合你的需要。
More on using the NSNotificationCenter
<强>更新强>:
第二种方法的优点是您的Cat
类和应用程序委托之间不需要任何特定的知识或依赖性。两个对象可以彼此独立地操作。 [UIApplication sharedApplication]
是iOS应用程序中运行的任何对象可用的单例,但同样,您不需要知道确切的类型。所需的唯一特定知识是通知名称,但即使是全局可访问的名称。