2013-03-03 115 views
0

这是一个陈旧的问题,我有一些编程经验,但Objective-c对我来说是全新的,我无法找到任何明确的定义整个客观C的概念。这里有一些我已经知道的理论:我不能直接访问类的实例变量,因此我必须使用属性或“访问器方法”来访问它。好的。我尝试了一些我的意思是通过访问方法,但嗯,这是全部错误。我想你可以帮我弄清楚这一点。如何访问AppDelegate.m中的某些实例类变量

这里是我的例子: 我有阶级猫和一个有关猫的信息的plist。 Plist存储宠物的名称和年龄。我想做这个:简单的看法,有textField,标签和一个按钮。标签 - 是一个当前的宠物名称,textField用于更改在textfield now方法中的猫名称(更改猫的名字听起来令人毛骨悚然,但这只是一个示例),以及一个将消息发送到更改名称函数的按钮。在我按下主页按钮后,我想通过AppDelegate.m文件将名称保存到文件中,这是一个问题,我将在下面介绍。

我不知道如何将代码封装到隐藏区域,直到您打开它,所以我不想在这里用大量的代码行打扰您的眼睛。我添加一个链接到代码和一些日志输出的屏幕。 (如果有人会说我怎么能做到这一点,我会在这里添加代码),但现在这里是链接: http://shlonger.com/680dc6cf21aa426c4bed107213ab4467

我无法访问应用程序工作时实现的对象,来自AppDelegate。我为类变量创建了一些属性和一些getter/setter方法,但是当我在AppDelegate中初始化Cat类时,它又创建了另一个具有默认设置(如plist文件)的对象。如何通过正确的方式通过AppDelegate保存当前设置?

对不起,有很长的问题描述。

+0

发布代码是获得帮助的最佳方式之一。一些提示,如果您知道具体方法中的问题,请发布该方法,并使用**相关**错误消息。如果我们需要更多,我们会让你知道。 – 2013-03-03 21:40:16

+0

如果我理解正确,你想在应用程序进入后台时保存你的Cat类。 – 2013-03-03 21:42:09

+0

@MikeD嗯我真的没有理解你,但如果你想在这里的代码,我可以发布它,这不是一个问题,如果你对我的问题有问题,我准备回答所有的问题:) – 2013-03-03 21:43:32

回答

3

您不一定需要与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应用程序中运行的任何对象的单例,但您不需要知道确切的类型。所需的唯一具体知识是通知名称,但即使是全球通用名称也是如此。

+0

我正在尝试第一种方法。错误发生在Xcode中,所以这将修复错误'AppDelegate *委托=(AppDelegate *)[[UIApplication sharedApplication]委托];' – 2013-03-03 22:21:46

+0

@flinth查看我的更新。 – 2013-03-03 22:26:59

+0

哦,谢谢迈克,这对我很有帮助。我不知道它现在如何工作,但我肯定会学到它。 – 2013-03-03 22:39:35