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。另外,根据你的设计,你可能想使theString
一个readwrite copy
属性,在这种情况下,你还可以得到一个setter方法为副本的任意字符串到theString
。)
已经这样做了,你的应用程序代理现在公开一个返回该字符串的方法。当你需要访问它比应用程序委托一个其他的实现文件,使用-[NSApplication delegate]
获得委托,然后使用getter方法来获取字符串:
// ChatController.m
#import "EchoAppDelegate.h"
- (void)someMethod {
// Get a reference to the application delegate instance
EchoAppDelegate *appDelegate = (EchoAppDelegate *)[NSApp delegate];
// Use the application delegate instance to get theString
NSString *theStringDiff = [appDelegate theString];
}
正如耶指出,你应该思考应用程序委托是否是保留该字符串的正确位置。应用程序委托人应该关注适用于整个应用程序的信息和行为。
你不会,那会破坏封装。制作一个API来揭示事物。也就是说,你的应用程序委托是这类信息的错误地方。 – jer 2011-05-29 01:52:24