2011-05-29 52 views
1

EchoAppDelegate.hObjective-C Mac OSX應用程序 - 從另一個代理獲取變量?

NSString *theString; 

EchoAppDelegate.m

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

ChatController.m

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

我會怎麼做呢?

+0

你不會,那會破壞封裝。製作一個API來揭示事物。也就是說,你的應用程序委託是這類信息的錯誤地方。 – jer 2011-05-29 01:52:24

回答

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。另外,根據你的設計,你可能想使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]; 
} 

正如耶指出,你應該思考應用程序委託是否是保留該字符串的正確位置。應用程序委託人應該關注適用於整個應用程序的信息和行爲。

+0

一百萬萬分! :) – 2011-05-29 02:16:21

+0

@Josh Heh,你會很快達到這一點。 :) – 2011-05-29 02:17:38

+0

緩慢但穩定。 – 2011-05-29 02:18:43

相關問題