2011-05-29 17 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

相关问题