external variables help

Discussion in 'iOS Programming' started by uaecasher, May 7, 2010.

  1. uaecasher macrumors 65816

    uaecasher

    Joined:
    Jan 29, 2009
    Location:
    Stillwater, OK
    #1
    hello,

    I'm trying to make a variable (string to be exact) that I can read it's value from any file in my project.

    I searched around and found that I can use "extern" to make an external variable, but I'm not sure how to declare it.

    I've tried to put it in my viewcontroller.h file in this form:

    Code:
    extern NSString *score;
    
    But I got this error:

    Code:
    
      "_score", referenced from:
    
          _score$non_lazy_ptr in TapsViewController.o
    
    
         (maybe you meant: _score$non_lazy_ptr)
    
    ld: symbol(s) not found
    collect2: ld returned 1 exit status
    
    
    
     
  2. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    This basically means your design is wrong. Put the string into a data model and access it sensibly. Either you application delegate or create a singleton object (or objects) and access via those.
     
  3. PhoneyDeveloper macrumors 68040

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #3
    The extern keyword tells the compiler that the storage for the variable is declared elsewhere. The error you're seeing is because you don't have the storage declared anywhere.

    The usual way to do this is

    Code:
    // .m file
    NSString *score;
    
    // .h file
    extern NSString *score;
    If you were to have the declaration without the extern keyword in a .h file then you would have duplicates of the storage in every compilation unit that included the header file.

    Another way to do this, of course, is to have the string be a file scope static and then use a method to access it.

    Code:
    // .m file
    static NSString* sScore;
    
    -(NSString*)score{ return sScore; }
     

Share This Page