Objective-C基础:在MyAppDelegate中声明的对象无法在另一个类中访问 [英] Objective-c basics: Object declared in MyAppDelegate not accessible in another class

查看:59
本文介绍了Objective-C基础:在MyAppDelegate中声明的对象无法在另一个类中访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序委托中声明了一个对象:

I have an object declared in my app delegate:

@interface MyAppDelegate : NSObject <UIApplicationDelegate> {
    ClassName *className;
}

在另一个类中,我包括应用程序委托:

In another class, I include the app delegate:

#import "MyAppDelegate.h"

@implementation AnotherClass
-(void)doMethod {
    [className doClassNameMethod];
}

由于 className 被设置,因此在编译时失败未声明。由于我已经包含MyAppDelegate(在其中声明了className),因此它应该不可访问吗?我需要AnotherClass.doMethod来访问在MyAppDelegate中创建的同一实例。

This fails at compile time due to className being undeclared. Shouldn't it be accessible, since I've included the MyAppDelegate, where className is declared? I need AnotherClass.doMethod to be accessing the same instance that is created in MyAppDelegate.

对此的任何帮助将不胜感激。谢谢。

Any help on this would be most appreciated. Thanks.

推荐答案

要从另一个类访问一个类中的实例变量,应创建一个属性。

To access a instance variable in one class from another class, you should create a property.

@interface MyAppDelegate : NSObject <UIApplicationDelegate> {
    ClassName *className;
}

@property (nonatomic, readonly) ClassName *className;

...
@end

来自另一类您然后可以像这样访问此属性:

From the other class you may then access this property like this:

@implementation AnotherClass
- (void) doMethod {
    MyAppDelegate *delegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
    [delegate.className doClassNameMethod];
}
@end

这篇关于Objective-C基础:在MyAppDelegate中声明的对象无法在另一个类中访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆