I would really like to do something I could do in Java but can't find out how to do in objective-c with regards to naming variables. In java:
private int var;
public void aMethod(int var)
{
this.var = var;
}
I'd really like to use the same variable name for a method parameter and a field in some cases. Is that possible? Thanks...
In Objective-C, any character , numeric or boolean literal prefixed with the '@' character will evaluate to a pointer to an NSNumber object (In this case), initialized with that value. C's type suffixes may be used to control the size of numeric literals. '@' is used a lot in the objective-C world.
An Objective-C method declaration includes the parameters as part of its name, using colons, like this: - (void)someMethodWithValue:(SomeType)value; As with the return type, the parameter type is specified in parentheses, just like a standard C type-cast.
Java static code analysis: Methods and field names should not be the same or differ only by capitalization.
Consider this header file:
@interface MYClass : NSObject {
@private
int var; // 1
}
@property(nonatomic, assign) int var; // 2
-(void)someMethodWithVar:(int)var; // 3
@end
In this case you have three instances of the symbol var
:
Since all three instances are different things the var
symbol can be freely reused, they do not clash. However when implementing someMethodWithVar:
you can get into trouble.
You could assign the property:
-(void)someMethodWithVar:(int)var {
self.var = var;
}
This will work, but will give you warning "local variable hides the instance variable". It will compile and work as expected. The local variable will have the highest presidence, but the local ivar is never address, so no problem.
You could try to assign the ivar directly:
-(void)someMethodWithVar:(int)var {
var = var;
}
Still the same warning but this time it is fatal! What you do is assigning the local variable to itself, a no-op.
You could try to assign the ivar by reference to self
:
-(void)someMethodWithVar:(int)var {
self->var = var;
}
Still a warning, but not fatal since you explicitly dereference the ivar through self
.
Now warnings are BAD, you should treat warnings as error, especially if you are new and not 100% sure of what you do.
There are two ways to remove the warning. The first way, that I use myself, is to always name instance variables with a _
character prefix. This way they never clash with anything, and it is very explicit what they are.
@interface MYClass : NSObject {
@private
int _var;
}
...
The second way is to change the argument name. Many of Apple's own methods historically do this by using a
or an
as a prefix.
-(void)someMethodWithVar:(int)aVar;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With