It's a month ago I was reading a line about that. I am not sure, but I think that if I call self.myInstanceVariable then it uses automatically getters/setters, but if I would call directly myInstanceVariable = #"Foo" for example, then I would bypass any getter/setter which would be really, really, reeeaaallly bad. Right/wrong?
EDIT: I tried this in XCode.
The implementation looks like this:
#implementation Test
#synthesize name;
+ (Test*)testWithName:(NSString*)name {
Test* test = [self alloc];
test.name = name;
return [test autorelease];
}
- (void)setName:(NSString*)newName {
NSLog(#"SETTER CALLED!!");
if(name != newName) {
[name release];
name = [newName retain];
}
}
- (NSString*)name {
NSLog(#"GETTER CALLED!!");
return name;
}
- (void)doWrongThing {
NSString *x = name;
NSLog(#"doWrongThing: %#", x);
}
- (void)doRightThing {
NSString *x = self.name;
NSLog(#"doRightThing: %#", x);
}
The test code looks like that:
Test *t = [Test testWithName:#"Swanzus Longus"];
//NSLog(#"%#", t.name);
[t doWrongThing];
[t doWrongThing];
[t doWrongThing];
[t doRightThing];
So after launching this code in another method (I just used an existing project ;) ), I received this output in the console:
2009-05-01 19:00:13.435 Demo[5909:20b] SETTER CALLED!!
2009-05-01 20:19:37.948 Demo[6167:20b] doWrongThing: Swanzus Longus
2009-05-01 20:19:37.949 Demo[6167:20b] doWrongThing: Swanzus Longus
2009-05-01 20:19:37.949 Demo[6167:20b] doWrongThing: Swanzus Longus
2009-05-01 20:19:37.950 Demo[6167:20b] GETTER CALLED!!
2009-05-01 20:19:37.965 Demo[6167:20b] doRightThing: Swanzus Longus
Like you see, you MUST use self.instanceVariableName in order to use the getters and setters (or you do the call in brackets, works too).
Confusion Alert: You must only use self if you hack around in a method of the object from which you want to access an instance variable. From the outside, when you call someObjectPointer.someInstanceVariable, it will automatically access the getters and setters (yep, I tried that out too).
Just thought someone would be interested in a little case study ;)
That is correct. If you directly use the variable, bypassing the getter/setter you could create bugs. The getter/setter may be responsible for retain and/or releasing the object as well as other things. This could result in crashes/memory leaks etc.
If you are aware that you are bypassing the getter/setter and take the right precautions, there is nothing wrong with accessing the variable directly.
Jesse has some good insight (+1 to you, sir).
The only circumstance under which I would consider explicitly calling the underlying member variable directly (thus bypassing the getter/setter) is when I have written the getter/setter myself, and know exactly what it is and isn't doing, and 99% of those times is when I'm just initializing the member in my constructor.
Just read the documentation
First, this is incorrect
Test* test = [self alloc];
correct is
Test* test = [[self alloc] init];
Second, if you write
#synthesize name;
methods
- (void)setName:(NSString*)newName
- (NSString*)name
will be generated(!! dot-syntax is just syntax-sugar !!) automatically
Third, when you write
myvar.itInstanceVariable
it translates to
[myvar itInstanceVariable]
and
myvar.itInstanceVariable = newValue
translates to
[myvar setItInstanceVariable:newValue]
About your comment, when you declare you property in that way
#property(nonatomic, retain) MyType *myVar;
and write in implementation
#synthesize myVar
it creates two methods
- (MyType*)myVar {
return myVar;
}
- (void)setMyVar:(MyType*)newVar {
if (myVar != newVar) {
[myVar release];
myVar = [newVar retain];
}
}
so you don't need to worry about reteaning/releasing
Yes, the property syntax calls the setter. In almost all cases, this is what you want, since it handles a lot of memory management correctly by default. Also, the property name, ivar name and getter/setter names can also all be different, so you may find cases where it doesn't look like self.myInstanceVar.
Also, just as a side note, you may or may not know this already, but there's no point to synthesizing a property if you're just going to write all the accessor methods anyway.
Related
I've recently discovered that there is no need to declare a getter as a property to use the dot notation. I don't know about other compiler versions, but this is true for Apple LLVM 3.1. Does anyone foresees any problems with it? So, basically:
---------Star.h----------
-(UInt32)age;
---------Star.m----------
-(UInt32)age
{
//get star age
return starAge;
}
---------RootViewController.m----------
{
...
//use this instead of [star age] even if there is no synthesized property "age"
NSLog(#"%i", star.age);
...
}
Your code is perfectly acceptable. A compiler wold do something similiar if you wrote:
---------Star.h----------
#property (readonly) UInt32 age;
---------Star.m----------
#synthesize age = starAge;
Your code is fine. Dot notation is just another way to invoke an instance method.
self.foo = bar; is the same as [self setFoo:bar];
bar = self.foo; is the same as bar = [self foo];
What does ARC make of that?
What happens if you try to compile :
- (void)setX:(NSInteger)x {
NSLog(#"New x is %i", x);
}
...
[self setX:100];
without declaring X as a property?
Even if it works I feel that it's good practice to add that simple extra line of code to declare it as a property even if all it does is make your code more readable.
I have an NSMutableArray in my class containing Ingredient objects. I want to check whether the name property of any of the ingredients matches a string, but I can't get the syntax quite right.
I'm really missing Linq and predictates.
-(BOOL) hasIngredient:(NSString *)ingredientName{
for (Ingredient *ingredient in ingredients) {
//if([ingredient isKindOfClass:[Ingredient class]]){
if ([ingredient->name isEqualToString:ingredientName]) {
return YES;
}
//}
}
return NO;
}
The foo->bar syntax directly accesses instance variables. You shouldn't do that. The syntax to access a property is:
object.property
or:
[object property]
Accessing a property is always a method call. If you have a property foo and do #synthesize foo;, the compiler generates a method named foo and setFoo: (if the property isn't readonly).
So you should have something like:
#property(nonatomic,readonly) NSString *name;
Replace readonly with copy if you want the name to be changeable (the reason to use copy instead of retain is because you could pass a mutable string and then later modify that mutable string, which would sure yield unexpected results; you avoid that by copying).
Now your method becomes:
-(BOOL) hasIngredient:(NSString *)ingredientName{
for (Ingredient *ingredient in ingredients) {
if ([[ingredient name] isEqual:ingredientName]) {
return YES;
}
}
return NO;
}
Instead of [ingredient name] you can also write ingredient.name here, but I personally like the former better since the later is also used for accessing members of a struct which is "cheap" whereas accessing a property always involves a method call and thus is "more expensive". But that's just a matter of taste.
Change
if ([ingredient->name isEqualToString:ingredientName])
to
if ([ingredient.name isEqualToString:ingredientName])
I am some what confused as to the difference between accessing an instance variable via self or just by name (when working inside the class).
For instance, take this class:
//In .h file:
#interface Register : NSObject {
NSString *mName;
}
- (id) initWithName:(NSString *) name;
//In .m file:
- (id) initWithName:(NSString *)name
{
if (self == [super init])
{
mName = name;
}
return self;
}
What's the difference between accessing the instance variable via
self.mName = name;
vs
mName = name;
Which isn't a #property and is not #sythenize'd.
Say it is this though, per this example:
//In .h file:
#interface Manange_My_ViewsViewController : UIViewController {
IBOutlet UILabel *countLabel;
}
#property (nonatomic, retain) IBOutlet UILabel *countLabel;
//In .m file:
#synthesize countLabel;
- (void) updateLabel:(NSUInteger)count
{
countLabel.text = [NSString stringWithFormat:#"%d", count];
}
But say I accessed countLabel as:
self.countLabel
What would be the difference?
Edit: Third example per users' answer:
Say it the iVar wasn't an IBOutlet:
//In .h file:
#interface Fake : NSObject {
NSString *mVar;
}
#property (nonatomic, retain) NSString *mVar;
//In .m file:
#synthesize mVar;
mVar = #"";
VS
self.mVar = #"";
Or is it the same - that in the first we are accessing the actual instance variable and in the second we're actually going through the auto created setter (via #synthesize)?
Thanks all!
Edit: Update in response to Peter Hosey ...
So your thinking the convention of mVarName is bad? I took that from my C++ days.
But what about the case when you do?
-(void) someMethod:(int) x
{
x = x;
}
You can't do that (Say 'x' is also a class variable)
But you can do:
-(void) someMethod:(int) x
{
mX = x;
}
But your saying its better to do:
-(void) someMethod:(int) x
{
self.x = x;
}
What's the difference between accessing the instance variable via
self.mName = name;
vs
mName = name;
The first is property access syntax. It translates to an accessor message to the object (in this case, self). That is, that statement implicitly translates to this message expression statement:
[self setMName:name];
(Awkward accessor names like that are why “mName” is a poor name for a property. There is property declaration syntax to work around that, letting you name the property “name” and your instance variable “mName” and map one to the other.)
The second example directly accesses the instance variable—no accessor message.
Which isn't a #property and is not #sythenize'd.
Say it is this though, …
If no property named “mName” is declared for a class, then you can't use property access syntax to access a property by that name on an instance of that class.
And it doesn't matter whether you synthesize the accessors, hand-wave them to a superclass with #dynamic, or define them yourself. That's how the object will respond to the accessor message, but the accessor message the compiler generates will be no different (since a property access could just as easily come from outside the class as from inside it).
Say it the iVar wasn't an IBOutlet:
That doesn't matter. IBOutlet only means anything to IB. Everything else doesn't care.
In fact, IBOutlet is currently just a macro that expands to nothing. After your code gets preprocessed, the word “IBOutlet” is no longer there, so the compiler never sees it. That's how little a difference it makes to anything but IB: None at all.
Edit in response to question edit
I said mName is bad as a property name, because of the accessor names that follow from it. The name of an instance variable is a separate issue, particularly since the property and ivar don't have to have the same name.
For a variable, be it an instance variable or a local variable, the choice of name or m_name or mName is purely a style choice.
someMethod: is generally the accessor, setX:. Within that method, self.x = x, which is [self setX:x], causes infinite recursion. So don't do that.
When someMethod: isn't the accessor (or init or dealloc), using the property is just fine and generally preferable. However, in that case, you're not likely to give one of its arguments the same name as an instance variable. When such a case could occur, name the local variable more specifically, because its purpose is more specific. This, too, is a style issue.
When it is the accessor, I name the local variable newX, having named the instance variable the same as the property, x. This is my own personal style; as I said, naming the property x, the ivar mX, and the local variable x is fine too (aside from the excessive brevity of this example).
OK, first off is the basic difference:
mVar = var;
This is just changing a value. That's it.
self.mVar = var;
This is equivalent to:
[self setMVar:var];
In other words, one invokes a method, the other does not. Using the #property syntax can give you some really neat benefits. For example, you get key-value coding compliance for free. That means that another object can observe this object's mVar property, and be automatically notified whenever it changes, without you doing anything. You don't get this if you just access the ivar directly. (Unless, of course, you implement it yourself. But why would you do that?)
You also get semi-free memory management. If you declare a property as (retain), then you don't have to [newValue retain] yourself. The synthesized method will do this for you (in both cases, you'd still have to [ivar release] in your dealloc method).
You also can get some degree of thread safety. If you don't declare a property as (nonatomic), then it is (by default) atomic (although that keyword does not exist; it's implied). That means that reading/updating the value of the property is an atomic operation. If you were to just access the ivar directly, you'd have to implement the atomicity yourself with a lock.
Basically, using the synthesized methods gets you some really neat stuff for free. The only reason I'd say to not use the #property syntax is if you have irrefutable evidence that invoking those methods is a bottleneck in your code. However, you'll be really hard pressed to come up with a situation where that would be the case.
First of all, with a read-only property--which an IBOutlet essentially is--it does not matter as much.
The key difference is that the property is actually calling the accessor method while the instance variable is being accessed directly.
Thus, for setting a retain property, using self and the accessor will release the old object and retain the new one. Setting the instance variable directly will NOT impact the retain counts of any objects.
Using #synthesize will generate standard accessors for you.
The key reason to use properties is that, since they are accessors, they can be read and/or modified from outside the class.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How does an underscore in front of a variable in a cocoa objective-c class work?
I've noticed that in a lot of the reference materials out there, I see that a lot of the time, variables are named _variable in the .h file, then are #synthesize'd in the .m file as
#synthesize variable = _variable;
Why is this done? What am I missing?
Thanks!
There is not consensus on this. Some people like to use it for clarity to separate out class variables, and as another responder noted to avoid conflict with incoming parameter names. Even in Apple sample code the use is mixed.
However, I greatly prefer to not use the _ prefix and have two strong reasons:
1) Some people think the _ is a good indicator of "private". My take is that NO class local variable should be accessed without a setter/getter (property) and thus they are ALL private - given that why not name them in a way easier to read and use autocomplete on? Any overlap in names from parameters is quickly revealed by the compiler, and avoided through more thoughtful naming of parameters (or internal variables).
2) (even better reason) - if you use "refactor" in XCode on an internal class var that is named the same as the property used to access it, the property and synthesize statement will also be renamed. If you use refactor on a class variable prefixed with an _, the property name will not be changed - just the synthesize mapping to the internal name. I pretty much never want the name to vary from the property to the real variable it exposes access to. That alone makes me never want to use _ as a variable prefix, since being able to shift names is just about the most useful thing you can do to improve code clarity.
Using that syntax is an option to make it more clear that the ivar and property are different things.
To code external to the class, there is no difference since it uses the property.
For code in the implementation of the class itself, it can make it more clear when the ivar is used versus the property.
For example, say we have an ivar/property for an NSNumber object:
#interface MyClass : NSObject {
NSNumber *num;
}
#property (nonatomic, retain) NSNumber *num;
- (void)doSomething;
#end
#implementation MyClass
#synthesize num;
- (void)doSomething {
// set the property, num is properly retained
self.num = [NSNumber numberWithInteger:1];
// accidentally set the ivar, num is NOT retained
num = [NSNumber numberWithInteger:2];
}
#end
and now using a different name for the ivar and property:
#interface MyClass : NSObject {
NSNumber *i_num;
}
#property (nonatomic, retain) NSNumber *num;
- (void)doSomething;
#end
#implementation MyClass
#synthesize num = i_num;
- (void)doSomething {
// set the property, num is properly retained
self.num = [NSNumber numberWithInteger:1];
// compiler error, there is no ivar named "num"
num = [NSNumber numberWithInteger:2];
// set the ivar, so it needs to be a retained object
i_num = [[NSNumber alloc] initWithInteger:3];
}
#end
Previous answers are missing the history behind this. Before Objective-C 2.0, there were no properties. So you’d have an object with instance variables like this:
#interface MyObject: NSObject {
NSArray *myArray;
}
#end
But how would you access them from other objects? the solution was to make setters and getters. But to avoid confusion, they would do it like this:
#interface MyObject: NSObject {
NSArray *_myArray;
}
- (NSArray *)myArray;
- (void)setMyArray:(NSArray *)myArray;
#end
The _ serves to clear up confusion between the instance variable _myArray and the method -myArray.
Sometimes people use mVarName (C++) and in Obj-c the style seems to be _varName.
One problem you can have, is imagine that your argument to a function is ...set:(int) x - BUT - you have an iVar called x...well your going to get the compiler crying about stuff like that - not to mention its confusing.
The m,_, whatever helps to show what are member properties of the class.
-(void) set:(int)x
{
x = x; // x is an ivar! heh
}
VS
-(void) set:(int)x
{
_x = x; // ahh I see!
}
This is purely convention. I suppose its common because when you make a method getter call like this:
[myObject variable]
you are actually calling a method, not accessing a variable directly. the _ in front makes it clear that you are talking about a variable. Personally, I find this syntax annoying and distracting. I find it unnecessary, but you are right, it does appear here and there.
I prefer not to use the '_' prefix because Apple does use it consistently. By avoiding the prefix I then have greater confidence that my ivars do not collide with Apple's when I extend a cocoa touch class. Since we do not have access to the base class' source this is really the only way I know of to avoid accidental reuse of existing private ivars.
Much like
Method names beginning with “_”, a single underscore character, are reserved for use by Apple.
My preference, following Google, is simply to append an underscore and explicitly synthesize (even if I'm reimplementing):
#synthesize varName=varName_;
If I see that trailing underscore outside of init..., dealloc or an accessor, I know something's fishy.
I've noticed in some of the examples ive seen that you will set a engine( class variable ) to a _engine ( ivar ). I don't get it. What's going on here?
Here is an example of what I'm saying:
#synthesize engine = _engine, delegate = _delegate
This syntax maps a property to an instance variable (ivar) with a different name.
So:
#synthesize engine = _engine;
will create property accessor methods that access the _engine ivar instead of engine. You can still access the propery as:
object.engine
More info in the Apple developer documentation on properties (section Property Implementation Directives)
The author wanted to make sure that there was no confusion between accessing the ivar directly and accessing via the setter/getter. If the names are the same, the usual case, it is easy to write:
engine = 0 instead of self.engine = 0; For an ivar that needs to be retained such as NSString this can cause errors in the retain counts.
There is also historic precedence of naming ivars with a leading "_", "m" or "f" so they wpuld be readily recognized as ivars.
The #synthezise keyword tells the Objective-C compiler to generate a getter and a setter method for your property. If you have defined:
#property(copy,nonatomic) NSString* name;
Then #synthesize name; will create these two methods for you, so that you do not have to implement them:
-(NSString*)name;
{
return name;
}
-(void)setName:(NSString*)newName;
{
if (name != newName) {
[name release];
name = [newValue copy];
}
}
By default the name of the instance variable that is used as the backing store for the synthesized property is named the same as the property. This is not always what you want, and you can then synthesize as #synthesize name = _otherName; to tell the compiler to instead generate this code for you:
-(NSString*)name;
{
return _otherName;
}
-(void)setName:(NSString*)newName;
{
if (_otherName != newName) {
[_otherName release];
_otherName = [newValue copy];
}
}
The reason you usually prefix the instance variables that are used as backing stores for properties with a underscore character '_' is to make help you to remember not to access them directly.
If the name of the ivar does not exactly match the name of the synthesized var then you need to map the ivar to the var. You might want to do this if you like prefixing your ivars with an underscore.