1

I'm reading my first book on Objective-C [Programming in Objective-C 4th Edition], I'm midway through the book but one thing that bugs me, is that it didn't explain WHY we initialize objects.

I tried playing around with the with objects, for example allocating their memory but not initiating them and everything in the program works the same as before.

I'd appreciate some example explaining this, also.

ab1428x
  • 794
  • 2
  • 8
  • 20

3 Answers3

6

The code within an init method is class specific - it performs whatever initialisation is required for that specific class. There are cases where a class does not need to perform any initialisation and thus removing this method call would have no effect.

However, by convention, you should always use init - what if someone were to add some required initialisation code to a class in the future?

See also:

alloc and init what do they actually do

Community
  • 1
  • 1
ColinE
  • 68,894
  • 15
  • 164
  • 232
3

To address you point of "everything works", the interesting thing about Objective-C is that alloc sets all instance variables to nil, and sending messages to nil doesn't do anything, it just returns nil, so in most of the cases you will not see a problem until you would try to do something illegal, consider a class like this

@interface MyObject : NSObject
@property (nonatomic, strong) NSString *string;
@end

@implementation MyObject
@end

Now if we'd just alloc it as:

MyObject *m = [MyObject alloc];

the instance variable _string, or property string would be nil, we could send different messages to it, like [string length] without any harm, since message to nil equals nil.

But say we then want to add this string to array, like

@[m.string]

Now you would get a exception, because NSArray cannot contain nil, only full blown objects. You can easily fix this by initializing your value inside MyObject.init.

Pretty contrived example, but hopefully shows the point of why everything doesn't break when you don't init :)

Dmitry Shevchenko
  • 31,814
  • 10
  • 56
  • 62
1

One of the main reasons why you should never use alloc's return value directly instead of using [[Class alloc] init]'s return value is that init might return a different object than alloc.

Apple's documentation mentions this:

Note: It’s possible for init to return a different object than was created by alloc, so it’s best practice to nest the calls as shown. Never initialize an object without reassigning any pointer to that object. As an example, don’t do this:

NSObject *someObject = [NSObject alloc];
[someObject init];

If the call to init returns some other object, you’ll be left with a pointer to the object that was originally allocated but never initialized.

Source: http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/ProgrammingWithObjectiveC/WorkingwithObjects/WorkingwithObjects.html

Johannes Fahrenkrug
  • 42,912
  • 19
  • 126
  • 165