gpt4 book ai didi

objective-c - NSString 适用于一种方法,但不适用于另一种方法

转载 作者:行者123 更新时间:2023-12-03 17:52:04 25 4
gpt4 key购买 nike

我有两种不同的方法来尝试从另一个类中获取变量。我更喜欢使用的第一个不起作用 - 我不喜欢使用的第二个却不起作用。有人可以解释一下为什么吗?

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

最佳答案

这是非常错误的:

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

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

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

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

或者,为了简洁起见:

AppDelegate *getString = [NSApp delegate];

关于objective-c - NSString 适用于一种方法,但不适用于另一种方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23978149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com