Accesing global variable giving linker error in objective C

房东的猫 提交于 2019-12-02 06:37:35

问题


I have declared a global variable like below

extern NSString *name;
@interface viewcontrollerOne{}

in implementation file i am accessing that global variable in some method like

-(void)someMethod
{
name = @"hello";
}

but this is giving linker error.

"name", referenced from: -[viewcontrollerOne someMethod] in viewcontrollerOne.o ld: symbol(s) not found for architecture i386 clang: error: linker command failed with exit code 1 (use -v to see invocation)


回答1:


The following is merely a declaration:

extern NSString * const name; // << side note: this should typically be const

It declares there is a symbol of NSString* named name. It does not create storage.

To do that, you will need to provide a definition for name. To do this, add the following to your .m file:

NSString * const name = @"hello";

If you want to set it in an instance method, as seen in your example, then you can declare it:

MONFile.h

extern NSString * name;

Define it:

MONFile.m

NSString * name = 0;

then you can write name = @"hello"; in your instance method.




回答2:


extern is tipically used to create contants. If you want to Create a global variable string, you can do it in the following way:

.h

+ (void)setName:(NSString*)name_in;

+ (NSString*)name;

.m

NSString* gName;

@implementation ...

+ (void)setName:(NSString*)name_in{
   gName = name_in;
}

+ (NSString*)name{
  return gName;
}


来源:https://stackoverflow.com/questions/13468321/accesing-global-variable-giving-linker-error-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!