2

I am just trying to understand life of variables with a throw away below code. I can see _inside and _outside retains when about instantiate new instance, while braces are not.

@interface ViewController (){
    NSString *_innBraces;
}

@end

NSString *_outside;

@implementation ViewController{
    NSString *_inmBraces;
}

NSString *_inside;

-(id)initWithInside:(NSString*)inside outside:(NSString*)outside nBraces:(NSString*)nBraces mBraces:(NSString*)mBraces{
    self = [super init];
    if (self) {
        _inside = inside;
        _outside = outside;
        _innBraces = nBraces;
        _inmBraces = mBraces;
        return self;
    }else{
        return nil;
    }
}
  1. Is there any difference between the place of declaration of _inside and _outside?
  2. Any difference between braces variables from where it is declared?
  3. Any difference between static variable declared same way vs _inside/_outside variable?
Saran
  • 6,274
  • 3
  • 39
  • 48

1 Answers1

5
  1. _inside and _outside are both declared as global variables.
  2. Since you appear to be declaring everything in the same file, there's no difference between _innBraces and _inmBraces, they are both instance variables in the class. If the @interface were in a header file, then you'd see a difference in scope between the two, since the _inmBraces would only be visible in your implementation file, and _innBraces will be visible in any file that includes the .h file.
  3. Neither of these are declared static. If they had been (preceding with the static keyword), then they would each be local in storage and namespace to the file where they are declared.

In the case of 1 and 3, they are both straight C declarations, and thus whether they are in the scope of the @implementation and @interface is doesn't make any difference. In Objective-C, there are no class variables, as such.

For class variables, the general process is to create a file-static variable of the form:

static NSString *sMyClassVariable;

within the implementation file. This variable, because it is static, will not be visible in any other file than your implementation file.

gaige
  • 17,263
  • 6
  • 57
  • 68