Difference between _ and self. in Objective-C
self.myString = @"test";
is exactly equivalent to writing [self setMyString:@"test"];
. Both of these are calling a method.
You could have written that method yourself. It might look something like this:
- (void)setMyString:(NSString*)newString
{
_myString = newString;
}
Because you used @synthesize
, you don't have to actually bother writing that method, you can just allow the compiler to write it for you.
So, from looking at that method, it looks like calling it will do the exact same thing as just assigning a value to the instance variable, right? Well, it's not so simple.
Firstly, you could write your own setter method. If you do so, your method would get called, and it could do all sorts of additional things as well as setting the variable. In that case, using self.myString =
would call your method, but doing _myString =
would not, and thus different functionality would be used.
Secondly, if you ever use Key Value Observing, the compiler does some very clever tricks. Behind the scenes, it subclasses your class, and overrides your setter method (whether it's one you wrote yourself or one generated by synthesize), in order to make the calls to willChangeValueForKey:
that are needed for Key Value Observing to work. You don't need to know how this works (although it's quite interesting if you want some bedtime reading!), but you do need to know that if you want Key Value Observing to work automatically, you have to use setter methods.
Thirdly, calling the setter method even if you're relying on synthesize to write one gives you flexibility for the future. You might want to do something extra whenever a value is changed, and at the point you discover you want to do that, you can manually write a setter method — if you're in the habit of always using self.myString =
, then you won't need to change the rest of your code to start calling the new method!
Fourthly, the same applies to subclasses. If someone else was to subclass your code, if you use the setters then they could override them to adjust the functionality.
Any time you access the instance variable directly, you're explicitly not providing a way for extra functionality to be hooked in at that point. Since you or someone else might want to hook in such functionality in the future, it pays to use the setters all the time, unless there's a good reason not to.
What's the difference between _variable & self.variable in Objective-C?
The difference is that:
the variable names with _
are instance variables.
self.variable
is calling a getter method on your object.
In your example, the instance variables are automatically generated and you don't need to synthesize your properties either.
The real important difference in your example comes into play if you are not using ARC-
self.variable
will retain an object for you if you mark the property with retain
or strong
_variable
does not address memory management at all
difference between self.myivar and self- myivar in objective-c
But in Objective-C is there any difference between self.myivar and self->myivar?
Yes, there's a difference. Assuming that foo
is a pointer to an object:
foo->bar
is equivalent to (*foo).bar
where the dot indicates the member access operator to get the instance variable bar
.
foo.bar
is equivalent to [foo bar]
; that is, it sends the message -bar
to the object pointed to by foo
. That may just return whatever is in foo
's bar
instance variable, but it may do other things. There may not even be an instance variable named bar
. As long as there's a method called -bar
, however, foo.bar
is valid. There should also be a -setBar:
method if you're using foo.bar
as the left hand side of an assignment, like: foo.bar = baz;
.
Note that although self
is a keyword in Objective-C, it always acts as a pointer to an object. There's nothing special about self
with respect to accessing properties or instance variables. I've used foo
as the name of the object pointer above to demonstrate that property/ivar access works the same way for any object pointer, but you could substitute self
for foo
above.
Difference between self.object and _object
As you mentioned one is an instance variable and the other is a property. In the earlier days of Objective-C there were different scenarios in which one would be better. Now they both act very similar and it is mainly a preference choice. There are arguments over which one is better but it really shouldn't matter which one you're using.
Difference between using self.variable and _variable when init these variables
The difference is simple: Using self.label = [[UILabel alloc] init]
will actually invoke the method [self setLabel:[[UILabel alloc] init]]
, and using _label = [[UILabel alloc] init]
will directly assign the value to the instance variable.
In practice what this means is that using the dot syntax is usually the best as the method invoked probably handles a lot of stuff for you, including:
- Memory management: For example, if you declare a property with attribute 'strong' or 'retain', then the method invoked should retain the object assigned.
- Key-Value Coding notifications: Maybe the class is key-value coding compliant for the property, which means the invoked method will notify the changes to observer objects.
Why would you not use the dot syntax? There are two potential reasons:
- To avoid side effects: A good practice is to not use the dot syntax inside an initializer method. This is because we want to assign the value but don't want the other side effects of the invoked method for safety reasons.
- Performance: This is probably rare, but maybe you are trying to implement a method with high performance and using instance variables directly can save the cost of invoking a method.
If you want to know more, I recommend reading this iOS guide which describes in more detail the ideas I mention here.
What is the difference between _name and self.name if name was a NSString
Assume you have in your .m file this line (and don't have any overriden methods to direct access to _name)
@synthesize name = _name;
It mean that property name
(self.name) will use variable _name when you try to access it. In this case self.name
is equal to _name
But if you have dynamic property for name, something like this :
-(NSString)name{
return @"1234";
}
then there is a difference. self.name
will always return 1234, but _name can be not equal to this value.
Example:
_name = @"555";
NSLog(_name);
NSLog(self.name);
Result:
2012-02-09 14:27:49.931 ExampleApp[803:207] 555
2012-02-09 14:27:49.933 ExampleApp[803:207] 1234
Difference b/w Objective C's self and C++'s this?
The main difference is that this
is a keyword, while self
is a variable. The result of this is that while this
always refers to the object that is executing a particular method, Objective-C methods are free to modify self
during execution. This is sometimes used by constructors, which set self = nil
on failure.
The reasons for doing so are:
- so that subclasses (which chain initialisers with
self = [super init]
) can see when the initialisation fails and know not to carry on in their own initialisers. - composing objects can see the failure and know that they don't have a valid component.
Some initialisers will set self
to a different, but valid, object. This can be used in class clusters, where the "abstract" class can generate a temporary instance while building the initialised object, but ultimately return a different object based on the properties that were built up during construction.
In addition, it means that you can do the usual things with variable names that confuse everyone that you can't do with keywords, such as defining a more local variable with the same name self
in a code block.
Related Topics
Looping Through Nsattributedstring Attributes to Increase Font Size
How to Debug "Terminated Due to Memory Error"
Nsdateformatter Milliseconds Bug
Adding Blur Effect to Background in Swift
Native Facebook App Does Not Open with Facebook Login in iOS 9
Creating a Navigationcontroller Programmatically (Swift)
Why Does My Programmatically Created Screenshot Look So Bad on iOS 7
How to Detect the Orientation of the Device on iOS
Using Ldap for Authentication in iOS
Open Uitableview Edit Action Buttons Programmatically
Uncaught Exception: This Class Is Not Key Value Coding-Compliant
How to Force a Hkquery to Load the Most Recent Steps Counts
How to Draw a "Speech Bubble" on an Iphone
How to Switch to Different Storyboard for iPhone 5
How to Get an Iphone's Device Name
This Certificate Has an Invalid Issuer:Keychain Marks All Certificates as "Invalid Issuer"