NSString使用一种方法但不使用另一种方法

时间:2014-06-01 08:47:17

标签: objective-c macos cocoa class nsstring

我有两种尝试从另一个类中获取变量的方法。我喜欢使用的第一个不起作用 - 第二个,我不喜欢它。有人可以解释一下原因吗?

AppDelegate.h

#import <Cocoa/Cocoa.h>

@interface AppDelegate : NSObject <NSApplicationDelegate> {

    NSString *someString;
}

@property (assign) IBOutlet NSWindow *window;
@property (retain, nonatomic) NSString *someString;

- (void)manualSetVariable;

@end

AppDelegate.m

#import "AppDelegate.h"
#import "GrabFromAppDelegate.h"

@implementation AppDelegate

@synthesize someString;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification  
{
    someString = @"The Variable";
    NSLog(@"In AppDelegate (1): %@",someString);

    GrabFromAppDelegate *getThis = [[GrabFromAppDelegate alloc] init];
    getThis.varSet = someString;
}

- (void)manualSetVariable {        // THIS METHOD WORKS (2)

    someString = @"The Variable";
    NSLog(@"In AppDelegate(2): %@",someString);
}

@end

GrabFromAppDelegate.h

 #import <Foundation/Foundation.h>

@interface GrabFromAppDelegate : NSObject {

    NSString *varSet;
    IBOutlet NSTextField *variable;
}

@property(retain, nonatomic) NSString *varSet;

- (IBAction)showVariable:(id)sender;
- (IBAction)manuallyGrabVariable:(id)sender;

@end

GrabFromAppDelegate.m

#import "GrabFromAppDelegate.h"
#import "AppDelegate.h"

@implementation GrabFromAppDelegate

@synthesize varSet;

- (IBAction)showVariable:(id)sender {

    if (varSet != NULL) {
        [variable setStringValue:[NSString stringWithString:varSet]];
        NSLog(@"Got String Using (1): %@",varSet);
    }
}

- (IBAction)manuallyGrabVariable:(id)sender {     // THIS METHOD WORKS (2)

    AppDelegate *getString = [[AppDelegate alloc] init];
    [getString manualSetVariable];

    if ([getString someString] != NULL) {
        [variable setStringValue:[NSString stringWithString:[getString someString]]];
        NSLog(@"Got String Using (2): %@",[getString someString]);
    }
}

@end

2 个答案:

答案 0 :(得分:1)

这是非常错误的:

AppDelegate *getString = [[AppDelegate alloc] init];

分配一个AppDelegate实例,但它不是[[NSApplication sharedApplication] delegate],因此getString实例永远不会执行applicationDidFinishLaunching方法,并且你的someString iVar永远不会被设置。如果你在init函数中设置someString,[[AppDelegate alloc] init]当然会调用init。但由于getString未附加到NSApplication个实例,因此没有将applicationDidFinishLaunching方法委托给它。

如果您想获得指向 应用程序委托的指针,您可以执行以下操作:

AppDelegate *getString = [[NSApplication sharedApplication] delegate];

或者,为了简洁起见:

AppDelegate *getString = [NSApp delegate];

答案 1 :(得分:0)

在第二种方法中,您从app delegate调用方法,并在someString变量中设置值,然后您得到响应。但是,如果要使用实例在appDelegate中为varibale设置值,则set值将传递给控制器​​类的特定实例,而不是所有实例。因此,您要么创建该变量的共享实例,要么调用该特定实例  通过showVariable方法获取值somestring。