self in objective C - ios

-(void)setFaceView:(FaceView *)faceView
{
_faceView= faceView;
self.faceView.dataSource = self;
}
I just started learning IOS programming with famous Stanford lectures on iTunes. I am currently at lecture 6 and I start to have difficulty catching up with the class.
It is a really basic thing, but I really don't understand how 'self' works. Can anyone teach me what 'self's in this code are doing?

self is an implicit parameter in objective-c of instance methods that refers to the object performing the method - see here: Messages to Self and Super
In this case, self.faceView is a call to the property accessor for faceView that is bound to the instance that runs this method, while the assignment _faceView= faceView; is assigning the input parameter faceView to the iVar _faceView. self.faceView.dataSource = self; assigns the object performing this method to the dataSource property of the object's faceView property.

self is the object itself. when you alloc an object. it sets aside enough memory to hold all the variables that class will use.
when you init the object however you attach that memory to self. self is essentially a "variable" (and i use the term loosely) that gives you access to all the functions of the object you are within.
if you have an object with the following method
+(BOOL) isThisWorking{ return YES;}
you would have to call the method on the class. Self is not involved.
however if you have a method
-(BOOL) isThisWorking{ return YES; }
then you would have a method attached to an instance of a class.
calling the first one would require you to call it on the class object itself.
[MyObject isThisWorking];
calling the second one would require you to call it on an instance.
MyObject *testObject = [[MyObject alloc] init];
[testObject isThisWorking];
when you are in a method within test object you will not have the 'testObject' to call methods on.
self fills that void.
if you come from another programming language you will be familiar with other constructs that do the same thing.
for instance in .net the object is "this"
and in old school vb if i remember correctly the object is "Me"

Related

Why init.. methods are required in Objective C?

Wherever I've read, it's written to never use an object without calling it's initializer function. And initializer functions always "have to" start with "init".
Is there a reason behind this naming (Does naming a method starting with init do something special)? What happens if I do not call the initializer function i.e. if I just do [MyClass alloc] and start using the object?
Alloc is called to allocate space in memory for the data type you are specifying. Whether it is NSString or NSNumber, calling Alloc will reserve the most efficient space in memory as possible for that data type (small or large).
Init is called to instantiate the class and superclass's important variables. These variables could include the Rect to recalculate a certain size in order to layout subviews, or perhaps instantiate with a delegate of some kind to perform some protocol upon creation. If it all becomes too much for you Objective-C does allow you to instantiate objects like MyClass *myObject = [MyClass new];
It may all seem redundant and a waste of time, but fortunately Swift has cut down tremendous amounts of redundancies like this in the new programming language. Now all you have to do is var myObject = MyClass() and if there are any custom initializers they would likely be writen like so var myObject = MyClass(frame: CGRectZero)
Happy coding!
I recommend reading the Apple Documentation on Object Initialization, and Initialization.
Is there a reason behind this naming (Does naming a method starting with init do something special)?
It is the convention, beginning a method name with init does not do anything special.
There are some minor quirks, such as if a method beginning with init returns type id, the compiler will convert the return type to instancetype, but these are barely worth mentioning.
What happens if I do not call the initializer function i.e. if I just do [MyClass alloc] and start using the object?
If you're using a standard SDK class, you'll likely run into a crash / exception. Initialization is used to set up the initial state of the instance variables, and without doing this can lead to undefined behaviour.
For a small example, if you called [[MyObject alloc] vegetable]; with the following class, you'd get nil returned because _vegetable hasn't been assigned.
#interface MyObject : NSObject
-(NSString*)vegetable;
#end
#implementation MyObject {
NSString *_vegetable;
}
-(instancetype)init {
self = [super init];
if (self) {
_vegetable = #"Cabbage";
}
return self;
}
-(NSString*)vegetable {
return _vegetable;
}
#end
It is the way you create objects in Objective-C. It is a hard requirement of the language. Creating an object in Objective-C is a 2 step process: alloc and init.
Under the covers, the reason you must call init is, wait for it, initialization.
The call to alloc creates a block of memory for your object and zeros it out. Calling init allows the object and it's ancestors to set things up so the object is ready to function. It initializes the object's memory and does other housekeeping that set the object up.
Further, every object's init method needs to call super init, so the initialization goes all the way up the object chain, all the way to NSObject. All the ancestor classes are designed to assume that their init method is called.

Passing owner reference to created objects

I need to pass the reference of a view controller to one of the object it creates. I have the following piece of code where I instantiate my object
//Method in OwnerClass
- (void) someMethod{
SomeObject *obj = [[SomeObject alloc] init];
obj.instanceVar = self.iVar;
}
Now in SomeObject I want to access the owner(instance of OwnerClass) which created it.
//Method in SomeObject
- (void) callback{
[ownerObj callMethod] //ownerObj is the instance of OwnerClass that created an instance of SomeObj
}
I want to know how do I access the instance of OwnerClass inside instance of SomeObject. Of course, I can simply write a property inside SomeObject like
#property(nonatomic) OwnerClass *ownerReference;
and assign it when I'm initializing SomeObject and access it from there.
What I want to is if there is any standard way of getting the owner. Something similar to
self.parentViewController
which is Apple's standard way of obtaining the parent of a particular view controller.
There is no general, formal concept of "Ownership" for objects in Objective C or the iOS SDK. So no, there is no standard "magic" way of doing what you want.
it's wrong to pass a reference from view to another view..
if you want to call method in another controller you can use protocols and delegate

What does init in Objective-C actually do?

+ (id)alloc;
and
- (id)init;
are methods from NSObject.h
The alloc does
+ (id)alloc {
return _objc_rootAlloc(self);
}
id
_objc_rootAlloc(Class cls)
{
#if 0 && __OBJC2__
// Skip over the +allocWithZone: call if the class doesn't override it.
// fixme not - this breaks ObjectAlloc
if (! ((class_t *)cls)->isa->hasCustomAWZ()) {
return class_createInstance(cls, 0);
}
#endif
return [cls allocWithZone: nil];
}
It does memory allocation, and return a class Instance.
But when I came to the init method, this is the implementation
- (id)init {
return _objc_rootInit(self);
}
id
_objc_rootInit(id obj)
{
// In practice, it will be hard to rely on this function.
// Many classes do not properly chain -init calls.
return obj;
}
It only return self object (NSObject) without doing any initialization.
The documentation also says the same thing.
"The init method defined in the NSObject class does no initialization; it simply returns self."
If that is the case, alloc method alone is sufficient.
Init method is only required for overridding.
Any explanation here?
This is the implementation source NSObject.mm
http://www.opensource.apple.com/source/objc4/objc4-532/runtime/NSObject.mm
alloc is to do with memory allocation while init (or initX etc., the init family) is to do with configuring that allocated memory as needed when an object is created - whether any particular class, now or in the future following some revision, needs to do any work in init is dependent on the semantics of that class. However as you don't know for any arbitrary class whether it's init needs to do any work you must call it, and as any arbitrary class does not know whether its superclass needs to do any initialisation to must call its superclasses init within its own init. For this chain to work NSObject must have an init, it so happens that it (currently, who knows in the future) does no work. NSObject's init is the end of the chain and the only one that does not need to call another init.
Confusion arises for some as many languages combine the two operations, allocation and initialisation, into one indivisible operation, e.g. new in Java. Indeed Cocoa has a new as well which is defined as alloc followed by init.
And Apple should really have written:
The init method defined in the NSObject class currently does no initialization; it simply returns self.
or simply said nothing.
HTH
CRD explained it pretty well.
I will state it more strongly, however.
The way you create a new object in Objective C is to use alloc/init.
You should always initialize every object, and custom init methods should always call [super init]. Consider failure to call init on ALL objects an error, and also consider calling [super init] in your custom init methods an error.

how to forbid the basic init method in a NSObject

I want to force user to use my own init method (for example -(id)initWithString:(NSString*)foo;) and not the basic [[myObject alloc]init];.
how can I do that?
All other answers here are outdated. There is a way to do this properly now!
While it is easy to just crash at runtime when somebody calls your method, compile-time checking would be far preferable.
Fortunately, this has been possible in Objective-C for a while.
Using LLVM, you can declare any method as unavailable in a class like so
- (void)aMethod __attribute__((unavailable("This method is not available")));
This will make the compiler complain when trying to call aMethod. Great!
Since - (id)init is just an ordinary method, you can prohibit calling of the default (or any other) initializer in this way.
Note, though, that this will not insure against the method being called using the dynamic aspects of the language, for instance via [object performSelector:#selector(aMethod)] etc. In the case of init, you won't even get a warning, because the init method is defined in other classes, and the compiler doesn't know enough to give you an undeclared selector warning.
So, to ensure against this, make sure that the init method crashes when being called (see Adam's answer).
If you want to disallow - (id)init in a framework, make sure to also disallow + (id)new, as this will just forward to init.
Javi Soto has written a small macro to forbid using the designated initializer faster and easier and to give nicer messages. You can find it here.
tl; dr
Swift:
private init() {}
Since all Swift classes include an internal init by default, you can change it to private to keep other classes from calling it.
Objective C:
Put this in your class's .h file.
- (instancetype)init NS_UNAVAILABLE;
This relies on an OS define that prevents the method named from being called.
The accepted answer is incorrect - you CAN do this, and it's very easy, you just have to be a bit explicit. Here's an example:
You have a class named "DontAllowInit" which you want to prevent people init'ing:
#implementation DontAllowInit
- (id)init
{
if( [self class] == [DontAllowInit class])
{
NSAssert(false, #"You cannot init this class directly. Instead, use a subclass e.g. AcceptableSubclass");
self = nil; // as per #uranusjr's answer, should assign to self before returning
}
else
self = [super init];
return nil;
}
Explanation:
When you call [super init], the class that was alloc'd was the SUBCLASS.
"self" is the instance - i.e. the thing that was init'd
"[self class]" is the class that was instantiated - which will be SUBCLASS when the SUBCLASS is calling [super init], or will be the SUPERCLASS when the SUPERCLASS is being called with plain [[SuperClass alloc] init]
So, when the superclass receives an "init" call, it just needs to check whether the alloc'd class is the same as its own class
Works perfectly. NB: I don't recommend this technique for "normal apps" because usually you INSTEAD want to use a Protocol.
HOWEVER ... when writing Libraries ... this technique is VERY valuable: you frequently want to "save (other developers) from themselves", and its easy to NSAssert and tell them "Oops! you tried to alloc/init the wrong class! Try class X instead...".
-(id) init
{
#throw [NSException exceptionWithName: #"MyExceptionName"
reason: #"-init is not allowed, use -initWithString: instead"
userInfo: nil];
}
-(id) initWithString: (NSString*) foo
{
self = [super init]; // OK because it calls NSObject's init, not yours
// etc
Throwing the exception is justified if you document that -init is not allowed and therefore using it is a programmer error. However, a better answer would be to make -init invoke -initWtihString: with some suitable default value i.e.
-(id) init
{
return [self initWithString: #""];
}
Short answer: you can't.
Longer answer: the best practice is to set your most detailed initializer as the designated initializer, as described here. 'init' will then call that initializer with sane, default values.
Another option is to 'assert(0)' or crash in another way inside the 'init', but this isn't a good solution.
I actually voted up Adam's answer, but would like to add some things to it.
First, it is strongly encouraged (as seem in auto-generated init methods in NSObject subclasses) that you check self against nil in inits. Also, I don't think class objects are guaranteed to be "equal" as in ==. I do this more like
- (id)init
{
NSAssert(NO, #"You are doing it wrong.");
self = [super init];
if ([self isKindOfClass:[InitNotAllowedClass class]])
self = nil;
return self;
}
Note that I use isKindOfClass: instead because IMHO if this class disallows init, it should disallow its descendants to have it as well. If one of its subclass want it back (which doesn't make sense for me), it should override it explicitly by calling my designated initializer.
But more importantly, whether you take the above approach or not, you should always have appropriate documentation. You should always clearly state which method is your designated initializer, try as best as you can to remind others not to use inappropriate initializers in documentation, and put some faith in other users/developers, instead of trying to "save everybody else's asses" with clever codes.

Access methods or property from another class without calling ViewDidLoad?

Typically, I would call another class method like this:
MyClass *class = [[MyClass alloc] init];
[class myMethod];
But the problem is that, it will call the ViewDidLoad. That is a problem for me.
Is there any way to access a property in another method or call a class in another method without calling the ViewDidLoad?
Thanks!
Edit1: So are you are saying that if I do this it will not call my VDL?:
MyClassB *classB = [[[MyClassB alloc] init] autorelease];
[classB.pauseButton setHidden:NO];
Also how about when I call a method will that trigger the ViewDidLoad?
Sure; refactor myMethod to not call viewDidLoad.
That is, if you call method a and method a calls b, but you don't want to call b, then you need to modify the implementation of a to sometimes not call b. Either by modifying a or creating a new method c on the class containing a that doesn't call b.
If the problem is that you are calling a method in the system frameworks and it is calling viewDidLoad when you don't want, then the answer is that you really can't do what you think you want to do. But that is just a symptom; the real answer is that your app's architecture needs to be revisited to better fit with the system's frameworks.
Edit1: So are you are saying that if I do this it will not call my
VDL?:
MyClassB *classB = [[[MyClassB alloc] init] autorelease];
That is creating a new instance of MyClassB. If there is already an instance being displayed on screen, then you most likely do not need a new instance and, yes, that is the reason why viewDidLoad is being called.
Either create an instance variable that can point to the already existing instance of classB or otherwise have a means of grabbing that instance; hang it off the app delegate or something.
Overall, it sounds like you are confused about what it means to instantiate an object vs. simply referring to one and how all that fits into the UIKit model of app creation. It is a bit tricky until you get the hang of it. Study some of the many examples that show how to use view controllers as they will likely have solved a similar problem.
You could create the view controller once and save it in an instance variable, then use the instance variable to call the method or access properties.
eg.
if(self.myClass==nil)
self.myClass = [[MyClass alloc] init];
[self.myClass doStuff];
[self.myClass.pauseButton setHidden:NO];

Resources