When to use self in Objective-C? - ios

// apply borders to the buttons
-(void)viewDidLoad
{
[super viewDidLoad];
[self.hostGameButton MH_applySnapStyle];
[self.joinGameButton MH_applySnapStyle];
[self.singlePlayerGameButton MH_applySnapStyle];
}
I am confused about this piece of code. If self is just referring to the instance of that object and when we use #property it creates an instance called _hostGameButton ... etc; why can't we just use this code instead?
[_hostGameButton MH_applySnapStyle];

You can, it's just not considered good practice or style. It breaks the encapsulation created by using properties, as well as the (usually desirable) KVO notifications the accessors generate. Modern Objective-C practice is to use properties for everything and only access the synthesized ivar in the init, dealloc (if necessary), and lazy accessor methods, if necessary.

Instances are the heart of the action in an Objective-C program. Most of the methods you’ll define when creating your own classes will be instance methods; most of the messages you’ll send in your code will call instance methods.
So when you create instance of something(like uibutton,uitext field) as property you can access
it anywhere in your.m file by using self. But if you create instance of it in a class you can access it only in that class but no where outside.

As per Apple Documentation, if you’re accessing an object’s properties from within its own implementation, in this case you should use self.

Related

Using property accessors on viewDidLoad - Objective C

As far as I know you should always use accessors to access or modify a property, except in two scenarios:
init
dealloc
Don’t Use Accessor Methods in Initializer Methods and dealloc The only
places you shouldn’t use accessor methods to set an instance variable
are in initializer methods and dealloc. To initialize a counter object
with a number object representing zero, you might implement an init.
This exceptions are because calling accessors when the view is not completely initialised might raise issues when overriding the setters/getters (https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html)
So, according to this the use of accessors on viewDidLoad should be perfectly fine, and even recommended, however in most of the codes available on internet developers use _ivars on viewDidLoad and I wonder why. Is there a reason for using property _ivars instead of accessors in viewDidLoad?
One of the most valuable post about using accessors in init/dealloc method
https://www.mikeash.com/pyblog/friday-qa-2009-11-27-using-accessors-in-init-and-dealloc.html
you should always use accessors to access or modify a property
Where did you read this?
When you want to access a property, you can use _ivar (or self->_ivar) to access the instance variable directly without passing by the getter, it would be faster that resolving and executing the getter.
However, if you use a custom getter then it won't be executed.
Often property accessors are overridden to update the view, which is inefficient if the view is not visible yet. So it is possible the code you found that ivar directly is using that to prevent that. However, much better is to use the property but check if the view is visible and only update if necessary. The same method can be called from viewWillAppear.

During init, Is there any way to avoid messaging self when dealing with properties from a super-class?

I've read that you're not supposed to send messages to 'self' during an init. Unfortunately, you can't directly access the ivars belonging to your superclass (as far as I can tell). This leads to the situation where you need to access / set up the superclasses ivar in some way, but have no way to do so other than messaging self. (For reference, I'm writing custom UIControls to encapsulate repeated concepts in my application; while a lot of the logic is shared, and thus belongs in a superclass, the exact layout of each control needs to vary).
For example, a custom control needs to have a button. That button is arranged different compared to each other object in the view depending on the subclass in question, so I need to reference it for layout. As far as I'm aware, unlike ViewControlllers, UIViews don't have any callbacks to let you know about lifecycle events like 'willAppear' or 'didLoad'; init is the only place to place the code -- and the tutorials I've read on creating custom UIControls put it there, as well.
Am I misunderstanding something, or do I have no choice but to violate the rule about messaging self in my scenario? (Or create an extra method that has to be called after init... creating a new convention that's basically saying 'first you init, then you REALLY init'!)
Unfortunately, you can't directly access the ivars belonging to your superclass (as far as I can tell)
That is only in situations when the base class declares ivars #private. If it does not, you can access ivars using the -> operator on self, like this:
self->myBaseIntVar = 123;
By default, ivars have #protected access, so you should be able to access them unless the designers of your superclass have specifically withdrew this possibility by specifying private access.
Am I misunderstanding something, or do I have no choice but to violate the rule about messaging self in my scenario?
Another choice is passing values to the designated initializer of your base class:
-(id)init {
if (self = [super initWithSomeProperty:123]) {
}
return self;
}

How does delegate call differ from normal method call ?

Whenever I wanted to inform something to parent class, I have used delegate instead of calling directly parent's functions. I have implemented like this...
eg:
CustomClass *custom = [[CustomClass alloc] init];
// assign delegate
custom.delegate = self; // Here we are giving parent instance like normal method call.
[custom helloDelegate];
In custom class, I have intimated parent like below....
-(void)helloDelegate
{
// send message the message to the delegate
[_delegate sayHello:self];
}
So my doubts , how does it differ from direct call?. Setting delegate variable with self is somewhat equal to giving the parent instance to child and let the child call the function whenever required, how does protocols help here or why do we need protocols? what is the advantage?
thanx
A working example of the advantage of using a delegate as opposed to using a direct relation.
Say you are writing a universal app. You have two view controllers in your code iPadViewController and iPhoneViewController and they both need to get data from a web service. So you create a class for you web service call webServiceDownloaderClass.
Now, both your view controllers need to be notified when the webServiceDownloaderClass has finished.
Your options here...
Option 1 strong coupling
In you iPadViewController you define a method - (void)webServiceDidGetArray:(NSArray *)array;. And in the iPhoneViewController you define the same method.
In order for the webServiceDownloaderClass to call these methods it now needs a reference to each of the controllers...
#property (nonatomic, strong) IPadViewController *iPadController;
#property (nonatomic, strong) IPhoneViewController *iPhoneController;
and then when it finishes it needs to determine which one to call...
if (iPadController) {
[iPadController webServiceDidGetArray];
}
etc....
The cons here are that the view controllers are sort of defining what the web service class does when it is finished. Also, if you add another controller you have another property and no actual guarantee that the controller you referenced actually has the method you are trying to call.
Option 2 delegation
In your we service class you define a protocol.
#protocol WebServiceDownloaderDelegate <NSObject>
- (void)webServiceDidGetArray:(NSArray *)array
#end
and a delegate...
#property (nonatomic, weak) id <WebServiceDownloaderDelegate> delegate;
Now you are defining the actions of the web service class in the web service class. And you only need one reference to any class wants to be the delegate. Also, any class can be the delegate. So now both the iPad and iPhone controller can be the delegate and by conforming the the protocol they are "promising" the web service class that they will implement the required method - (void)webServiceDidGetArray:(NSArray *)array;.
Of course, this is just one case where delegates can be useful.
There are also cases for when you should possibly use a direct relationship rather than delegation.
your question is really about the difference between subclassing rather than implementing protocols (or interfaces in other languages like java)..
with delegates, you are implementing a protocol.. (which is a contract between the class referencing the delegate and the delegate itself).. this gives you more flexibility than subclassing because with subclassing you are automatically inheriting all the methods in the superclass (which is far more restricting than simply using some of the methods of another class.. in other words: subclassing = is a relationship.. whereas as implementing a protocol (same as delegation) = has a relationship.
if you read any book about design patterns.. they will talk extensively about the advantages of loose coupling your code and writing code that prevents modification but allows extension etc etc.. basically using delegation rather than subclassing is one way of fulfilling those design best practices.
A delegate call is not different from an ordinary method call!
What is different is how things are used, and this has nothing to do with the call mechanism. Delegates are used to decouple the definition of the code providing the delegate service from the code "consuming" the delegate service, so that the "consumer" (which, oddly, is usually a service on behalf of the delegate provider) does not have to be coded to know about THAT SPECIFIC delegate provider.
In Objective C delegates are commonly implemented using "protocols", but this is far from the only use of protocols. Objective C uses them extensively in providing common interfaces among the various Cocoa classes.
And, in limited circumstances, one can legitimately implement a delegate using a common superclass rather than a protocol.
If you have two classes that are part of the same development effort and which would not be likely to ever be used apart from each other, there is no need to employ the delegate "pattern" to facilitate communication between them, even though they are is a service-consumer/service-provider relationship. The only reason to do so would be "on spec", in case the "service" were ever reused unchanged in a different project.

Properties and their backing ivars

Hi imagine I have properties in the .h file:
#property (nonatomic) NSString * myText;
#property (nonatomic) SomeClass * someObj;
Now, in the class implementation.
Say, I didn't forget to use synthesize, and I called:
#synthesize myText, someObj;
Now say in code I forget to put self before the property name (and directly refer to the ivar):
myText = #"Hello";
someObj = [[SomeClass alloc] init];
My question is: is this a problem? What problems can it result in? Or it is no big deal?
ps. Say I am using ARC.
My question is: is this a problem?
This is called "direct ivar access". In some cases, it's not a problem, but a necessity. Initializers, dealloc, and accessors (setters/getters) are where you should be accessing self's ivars directly. In almost every other case, you would favor the accessor.
Directly accessing ivars of instances other than self should be avoided. Easy problem here is that you may read or write at an invalid address (undefined behavior), much like a C struct. When a messaged object is nil, the implementation of that message is not executed.
What problems can it result in?
Biggest two:
You won't get KVO notifications for these changes
And you are typically bypassing the implementation which provides the correct semantics (that can be justified). Semantics in this case may equate to memory management, copying, synchronization, or other consequences of a change of state. If, say, a setter is overridden, then you are bypassing any subclass override of that setter, which may leave the object in an inconsistent state.
See also: Why would you use an ivar?
For clarity, I recommend always using
self.propertyname
as opposed to
propertyname
as this removed any confusion between what variable belong to the class or have been declared locally above in the method.
To enforce this, try to avoid using #synthesize at all, which is only needed if you provide both custom getter and setter (but not one or the other)
The compiler automatically allows you to use _propertyname in the getter/setter (which is necessary to prevent recursive calls of the function)
You should not access the underlying instance variables by accident, only if you plan to do so.
Unexpected side effects may be that KVO doesn't work, overriding accessor methods are not called and the copyand atomic attributes have no effect.
You don't need to use #synthesize since Xcode 4.4, if you use default synthesis the compiler does an equivalent of
#synthesize myText = _myText;
so that
_myText = #"Hello";
self->_myText = #"Hello";
are equivalent and myText = #"Hello"; results in an "undefined identifier" compiler error.
If you use just #synthesize myText the compiler does (for backward compatibility reasons):
#synthesize myText = myText;
which is error prone.
Note that there are valid reasons to use the underlying instance variables instead of the accessor - but it's bad style to do this by accident.
For 30 years now, the recommended practice has been:
use getter/setter methods or the new . operator to read and write ivars.
only access ivars directly when you must.
pick ivar names to prevent accidentally using them, unless the ivar is one that will always be accessed directly (that is why the default behaviour and convention is to prefix ivars with an underscore).
You need to access ivars directly in a few situations:
Manual memory management requires it. You won't need this if ARC is enabled.
If you are going to read the variable variable millions of times in quick succession, and you can't assign it to a temporary variable for some reason.
When you're working with low level C API, it probably needs a pointer to the ivar, Apples libxml2 sample code accesses ivars directly for example.
When you are writing the getter or setter method yourself, instead of using the default #synthesize implementation. I personally do this all the time.
Aside from these situations (and a few others), do not access ivars directly. And prefix all ivars with an underscore, to make sure you don't accidentally access them and to prevent them appearing in xcode's autocomplete/intellisense while you code.
The two main reasons for the convention are:
Getter/setter methods and properties can be kept around when the underlaying memory structure of your class changes. If you rename an ivar, all code that reads the ivar will break, so best to have zero code or almost no code that accesses ivars directly.
Subclasses can override getters and setters. They cannot override ivars. Some people think subclasses shouldn't be allowed to override getters and setters - these people are wrong. Being able to override things is the entire point of creating a subclass.
Fundamental features like KVC and KVO can fall apart if you access ivars directly.
Of course, you can do whatever you want. But the convention has been around for decades now and it works. There is no reason not to follow it.
Contrary to what other answers seem to agree upon, I would recommend to always use direct ivar access unless you are very clear about what you are doing.
My reasoning is simple:
With ARC, it's not even more complicated to use direct property access, just assign a
value to the ivar and ARC takes care of the memory management.
(And this is my main point:) Property accessors may have side-effects.
This is not only true for property accessors you write, but may also be true for
subclasses of the class you are implementing.
Now these accessors defined in subclasses may very well rely on state that the subclass
sets up in it's initializer, which has not executed at this point, so you calling those
accessors might lead to anything from undefined state of your object to your application
throwing exceptions and crashing.
Now, not every class may be designed to be subclassed, but I think it's better to just use one style everywhere instead of being inconsistent depending on the class you are currently writing.
On a side note: I would also recommend to prefix the name of every ivar with an _, as the compiler will do automatically for your properties when you don't #synthesize them.

Difference between _ and self. in Objective-C

Is there a difference between using the underscore and using the self keyword in Objective-C when calling an #property?
Property declaration:
#property (weak, nonatomic) NSString *myString;
Calling #synthesize on the property:
#synthesize myString = _myString;
Is there a difference if I want to use it in my code? When? In the getter/setter?
self.myString = #"test";
_myString = #"test";
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.
You are correct - the first version (self.myString) calls the synthesized getter/setter and the second version access the private member variable directly.
It looks like you are using ARC, so in that case it doesn't make that much of a difference. However, if you aren't using ARC, it can make a difference as assigning to the private member directly won't trigger the automatic retain/release or copy/release logic that is generated for you by using synthesize.
The _ (underscore) is simply a convention, as explained in this question.
When you don't prefix a property access with self., you are accessing the underlying variable directly, as in a c struct. In general, you should only ever do this in your init methods and in custom property accessors. This allows stuff like computed properties and KVC to work as intended.
There is a tip not mentionend, the access using underscore is faster and the access using self is safer (KVC). Maybe this can summarise when you have to use each one.

Resources