我对cocoa和Xcode很新,我已经完成了一些基本的C编码,但我非常厌恶Objective-c和cocoa,所以请原谅我犯下的任何愚蠢错误。我的问题是我正在使用的这些全局变量。 我在头文件中声明了一个全局NSString变量,它在主文件中使用如下:
//AppController.h
-(IBAction)button1:(id)sender;
-(IBAction)button2:(id)sender;
extern NSString *hi
//AppController.m
-(IBAction)button1:(id)sender
{
NSString *const hi = @"Hello";
}
-(IBAction)button2:(id)sender;
{
NSLog (@"%@", hi);
}
但是,当我单击运行时,构建失败并收到错误消息:
“_ hi”,引自:
一些额外信息:
Undefined symbols for architecture x86_64: "_hi", referenced from: -[AppController gallery:] in AppController.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
如果你知道这意味着什么和/或如何解决它,请帮助我。感谢
答案 0 :(得分:4)
您需要为hi
提供全局定义。移动您的声明:
NSString *const hi = @"Hello";
到任何方法的外的某个地方。我不确定你想要button1:
做什么,但对你的实现来说似乎没有必要。
答案 1 :(得分:2)
我认为卢克喜欢:
单击按钮一后,将字符串设置为特定值,
并在单击按钮2后再次检索它。
<强> AppController.h 强>
#import <Cocoa/Cocoa.h>
@interface AppController : NSObject{
NSString * string;
}
-(IBAction)button1:(id)sender;
-(IBAction)button2:(id)sender;
@end
<强> AppController.m 强>
#import "AppController.h"
@implementation AppController
-(IBAction)button1:(id)sender
{
string = @"Hello";
}
-(IBAction)button2:(id)sender;
{
NSLog (@"%@", string);
}
@end
答案 2 :(得分:2)
在定义全局变量和常量字符串等时,通常我会这样做:
MDAppController.h
:
#import <Cocoa/Cocoa.h>
extern NSString * const MDShouldShowInspectorKey;
extern NSString * const MDShouldShowViewOptionsKey;
extern BOOL MDShouldShowInspector;
extern BOOL MDShouldShowViewOptions;
@interface MDAppController : NSObject <NSApplicationDelegate> {
IBOutlet NSWindow *window;
}
- (IBAction)hideInspector:(id)sender;
@end
MDAppController.m
:
#import "MDAppController.h"
NSString * const MDShouldShowInspectorKey = @"MDShouldShowInspector";
NSString * const MDShouldShowViewOptionsKey = @"MDShouldShowViewOptions";
BOOL MDShouldShowInspector = NO; // default value
BOOL MDShouldShowViewOptions = YES; // default value
@implementation MDAppController
+ (void)initialize {
NSMutableDictionary *defaultValues = [NSMutableDictionary dictionary];
[defaultValues setObject:
[NSNumber numberWithBool:MDShouldShowInspector]
forKey:MDShouldShowInspectorKey];
[defaultValues setObject:
[NSNumber numberWithBool:MDShouldShowViewOptions]
forKey:MDShouldShowViewOptionsKey];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultValues];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSUserDefaults *uD = [NSUserDefaults standardUserDefaults];
MDShouldShowInspector = [[uD objectForKey:MDShouldShowInspectorKey] boolValue];
MDShouldShowViewOptions = [[uD objectForKey:MDShouldShowViewOptionsKey] boolValue];
}
- (IBAction)hideInspector:(id)sender {
NSLog(@"MDShouldShowViewOptionsKey == %@", MDShouldShowViewOptionsKey);
MDShouldShowInspector = NO;
[[NSUserDefaults standardUserDefaults]
setObject:[NSNumber numberWithBool:MDShouldShowInspector]
forKey:MDShouldShowInspectorKey];
}
@end
答案 3 :(得分:0)
我的问题是你为什么要成为外界?这里最好的方法是创建一个单例,你应该把所有成员作为一个类的一部分,并避免任何全局。 希望这有帮助