Accesing global variable giving linker error in objective C

前端 未结 2 1098
轻奢々
轻奢々 2021-01-23 13:32

I have declared a global variable like below

extern NSString *name;
@interface viewcontrollerOne{}

in implementation file i am accessing that g

相关标签:
2条回答
  • 2021-01-23 13:54

    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.

    0 讨论(0)
  • 2021-01-23 14:15

    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;
    }
    
    0 讨论(0)
提交回复
热议问题