If I have an NSObject
subclass which either has no -init
method or simply does nothing in -init
, is there any difference between an instance created these two ways:
MyClass *instance = [MyClass alloc];
MyClass *instance = [[MyClass alloc] init];
By "does nothing in -init
" I mean
- (id)init {
self = [super init];
if (self) {
}
return self;
}
Since NSObject
's -init
method itself does nothing, I can't see there being any difference, but of course the advice is that you must call -init
to properly prepare an object.
Here's the snippet from NSObject
's -init
method which got me wondering about this:
The init method defined in the NSObject class does no initialization; it simply returns self.
No. You never need to explicitly call a destructor (except with placement new ). A class's destructor (whether or not you explicitly define one) automagically invokes the destructors for member objects. They are destroyed in the reverse order they appear within the declaration for the class.
A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete .
When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.
The new operator creates a new instance of a type. You can also use the new keyword as a member declaration modifier or a generic type constraint.
If I have an
NSObject
subclass which either has no-init
method or simply does nothing in-init
, is there any difference between an instance created these two ways:
MyClass *instance = [MyClass alloc];
MyClass *instance = [[MyClass alloc] init];
Technically, there is no difference.
But that doesn't mean you should use a bare +alloc
to ever create an instance for a variety of reasons.
First, it is the principal of the thing. Objective-C coding standards say +alloc
should always be followed by -init
.
Secondly, it is all about consistency and code maintenance. What happens when you refactor MyClass
to be a subclass of some class where the designated initializer is actually critical? A nasty, hard to figure out, bug is what happens.
Of relevance, note that the use of +new
has been all but deprecated for a similar reason. It makes refactoring tedious (dammit! gotta break apart THIS call site, too!) and the convenience factor is exceedingly minimal.
No, it's not and you're not doing nothing, you're calling [super init]
and that does a lot to initialize your superclasses up until NSObject
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With