user726102
user726102

Reputation: 55

noob here- objective C pointer having different addresses?

NSString *msgg = [NSString alloc];
NSLog(@" address that msgg is holding is %p ", msgg);
msgg = [msgg init];
NSLog(@" address that msgg is holding is %p ", msgg);

Now alloc means objective c goes to the memomr and carves out a space. the address of this space is held in the pointer msgg.

The instance is also created in the same space. So I am expecting the address to remain same. But my output to console is as follows.Please note the addresses are different

BasicObjC[3064:10b]  address that msgg is holding is 0x103340 
BasicObjC[3064:10b]  address that msgg is holding is 0xa0289328

Upvotes: 3

Views: 138

Answers (3)

drewag
drewag

Reputation: 94733

In "normal" classes this should be true (but you should not depend on it). But, in the case of NSString (and actually many of apple's data classes: NSData, UIImage ), this class is actually a "Class Cluster". You use an object called "NSString" but the class that you get back is a secret other class (most likely NSCFString). There are other secret classes behind NSString. When you alloc an NSString it makes a "dummy" object, and then when you call init with a specific value, it determines the secret class that it wants to actually give you (hence the different address).

A more understandable example would be UIImage. UIImage can be created with many different image types (png, jpg, etc.). To you it just looks like UIImage, but when you call init, it will actually return a different subclass for each type of image that you are referencing.

Upvotes: 2

NSResponder
NSResponder

Reputation: 16861

The reason why we always nest the -alloc and -init messages is that -init doesn't have to return self. It is free to return a newly created object.

Upvotes: 1

user557219
user557219

Reputation:

There’s no guarantee that the instance returned by +alloc is the same instance returned by a subsequent initialiser (e.g. -init).

For example, one of the initialisers in NSString might return a literal string that’s been pre-allocated. In that case, the instance that was created via +alloc is deallocated and the initialiser returns the address of the literal string instead.

Upvotes: 2

Related Questions