Reputation:
I am learning iOS programming, so please bear with me.
Imagine I have a class in which I want to just have a simple init
method (no params) and
initialization of my instance variables I want to be done via properties.
For example:
@interface MyClass : NSObject
{
}
@property (nonatomic) SomeClass1 *p1;
@property (nonatomic) SomeClass2 *p2;
@property (nonatomic) SomeClass3 *p3;
As I mentioned I have a simple init
, no parameters. Nothing, I don't even implement it, it is inherited from NSObject.
So, now, if someone wants to initialize p1,p2,p3
variables of MyClass
object, can't there be such problematic situations, when someone sets:
1. MyClass *object = [[MyClass alloc] init];
2. [[object p1] doSomething];
where the 2nd line will raise an exception, because there was no for example object.p1 = [[SomeClass1 alloc] init]
call before it?
Upvotes: 1
Views: 73
Reputation: 29946
It won't raise an exception, because in Objective-C a method call on a nil
object pointer is a no-op -- nothing happens. This is different from C++ where calling an instance method on a NULL
pointer would cause a crash.
This actually turns out to be pretty useful, because it means you can chain method calls without having to worry that an intermediate method returns nil
. Like this:
[[[[object p1] doSomething] doSomethingElse] doAnotherThing];
If messaging a nil
object crashed or raised an exception, you would have to check the result of each of those four method calls in order to be safe.
For what it's worth, in general, if your object needs a valid value for p1
in order to work correctly or be useful, it makes sense to make that object a parameter to the -init
method.
Upvotes: 4