Reputation: 326
In Xcode / Objective C: Is there a syntax that you can force access to a global variable. I notice that a class variable silently hides any global variable. See example. Not suggesting it's a good idea but just curious.
int someVariable = 56;
@implementation Example {
int someVariable;
}
- (void)print {
printf("Var=%i\n", someVariable);
}
Upvotes: 2
Views: 128
Reputation: 15597
The convention used by Apple and most Objective-C developers is to capitalize global names, and if the project uses a prefix, to prefix them as well. So for example:
int SomeVariable = 56;
or
int XYZSomeVariable = 56;
That way your global names can never collide with names of instance variables (not class variables, by the way -- there is no such thing in Objective-C), local variables, or arguments so long as you observe the other half of the convention: local names always begin with a lowercase letter.
Edit
I should also mention that there's a longstanding convention in Objective-C to prefix instance variable names with an underscore, which would also help avoid the problem. In fact, the LLVM 4.0 auto synthesis feature now automatically synthesizes ivars with an underscore prefix for declared properties unless you tell it not to. So for example, if you had declared the instance variable in your example as follows:
@implementation Example
{
int _someVariable;
}
...the ivar couldn't have shadowed the global variable.
Upvotes: 5