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