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

obj*_*001 1 macos cocoa objective-c nsstring

EchoAppDelegate.h

NSString *theString;
Run Code Online (Sandbox Code Playgroud)

EchoAppDelegate.m

/////being declared somewhere here//////
theString = [lastUserInputJabber stringValue];
Run Code Online (Sandbox Code Playgroud)

ChatController.m

//Get theString variable from echoappdelegate
NSString *theStringDiff = theString;
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

小智 5

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

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

// EchoAppDelegate.m
@implementation EchoAppDelegate
- (NSString *)theString { return theString; }
@end
Run Code Online (Sandbox Code Playgroud)

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

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

// EchoAppDelegate.m
@implementation EchoAppDelegate
@synthesize theString;
@end
Run Code Online (Sandbox Code Playgroud)

(根据您的目标/编译器,您可能不需要声明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];
}
Run Code Online (Sandbox Code Playgroud)

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