Search code examples
objective-civar

Difference between ivars and (global?) variables defined outside the brackets


What is the difference between

@implementation aClass {
   aType *aVariable
}

- (void)aMethod: {
}

and

@implementation bClass

bType *bVariable

- (void)bMethod: {
}

Is bVariable global?


Solution

  • Is bVariable global?

    Yes.

    Objective-C is an extension of C and this is a standard C global variable declaration.

    You probably should also look up the meanings of static and extern in relation to global variables in C.

    HTH

    Addendum

    So back to the first question, the difference is that I can't define bVariable again in my entire project, while the term aVariable can be reused?

    Short answer: No, at least not how you've expressed the question.

    Long answer: What you have are two declarations each of which declare a variable and associate a name (or identifier) - aVariable, bVariable - with that variable. As well as a type, which is part of the declaration, a variable has a lifetime - how long the variable exists - and a scope - the part of the program in which the variable is accessible. Scopes can nest, and inner scopes can contain declarations which use the same name's as those in outer scopes, which results in hiding - the variable in the outer scope cannot be directly accessed via its name.

    A global variable is one whose lifetime is the whole execution of the program, however the scope in which a global variable is (directly) accessible need not be the whole program (c.f. the static qualifier in (Objective-)C), and different global variables with non-overlapping scopes can have the same name.

    An instance variable is one whose lifetime is the same as that of its owning class instance, and whose scope is the members of the class.

    There are also local variables, whose lifetime and scope is the containing method, function, block etc. that declare them.

    The above is just a quick summary, you should look up the meanings of the all italicised terms.