Objective-C Mac OSX应用程序 - 从另一个委托获取变量?

时间:2011-05-29 01:27:20

标签: objective-c macos cocoa nsstring

EchoAppDelegate.h

NSString *theString;

EchoAppDelegate.m

/////being declared somewhere here//////
theString = [lastUserInputJabber stringValue];

ChatController.m

//Get theString variable from echoappdelegate
NSString *theStringDiff = theString;

我该怎么做?

1 个答案:

答案 0 :(得分:5)

EchoAppDelegate必须提供一个返回该字符串的方法,或者将该字符串设为公共ivar。例如,您可以实现一个getter方法,如:

// EchoAppDelegate.h
@interface EchoAppDelegate : NSObject <NSApplicationDelegate> {
    NSString *theString;
}
- (NSString *)theString;
@end

// EchoAppDelegate.m
@implementation EchoAppDelegate
- (NSString *)theString { return theString; }
@end

或使其成为声明的属性,并让Objective-C自动提供getter方法:

// EchoAppDelegate.h
@interface EchoAppDelegate : NSObject <NSApplicationDelegate> {
    NSString *theString;
}
@property (readonly) NSString *theString;
@end

// EchoAppDelegate.m
@implementation EchoAppDelegate
@synthesize theString;
@end

(根据您的目标/编译器,您可能不需要声明ivar - 现代运行时和最近的编译器可以自动为声明的属性创建支持ivars。此外,根据您的设计,您可能想要{{ 1}} theString属性,在这种情况下,您还将获得一个将任意字符串复制到readwrite copy的setter方法。)

完成此操作后,您的应用程序委托现在公开了一个返回该字符串的方法。当您需要在应用程序委托之外的实现文件中访问它时,使用theString获取委托,然后使用getter方法获取字符串:

-[NSApplication delegate]

正如jer所指出的,您应该思考应用程序委托是否是保留该字符串的正确位置。应用程序委托应关注适用于整个应用程序的信息和行为。

相关问题