user3492899
user3492899

Reputation: 21

object reference is same in function calling

 -(UserDetail *)functionCheck :(NSString *)str
 {
    UserDetail *d2=[[UserDetail alloc] init];
    NSLog(@"check address::::::> %p",&d2);
    d2.auth_token=str;
    return  d2;

 }

whenever i am calling functionCheck() function print same address

check address::::::> 0xbfffd500

means it allocate same address. how to deallocate UserDetail d2 object after return.

Upvotes: 0

Views: 46

Answers (3)

Hermann Klecker
Hermann Klecker

Reputation: 14068

Apparently you are in an ARC environment. The allocated space gets deallocated as soon as functionCheck is left AND its return value, the newly allocated object, is not stored by any kind of strong reference. We say that no object takes ownership on the newly created UserDetail instance.

With ARC the object is then free to be destroyed.

Without ARC it is kinda different. Unless the return value is released by the caller or somewhere else, your code would be memory leaking here. d2 would remain allcoated although it is not referencable from anywhere and next time functionCheck is called a new object would be allocated and get a different address.

But yours gets the same address every time when a new instance of UserDetail is allocated within functionCheck and assigned to d2. That means that the earlier instance must have been deallocated in the meantime.

Unless that very part of the heap is occupied by other objects that may have been allocated in between, or other parts of the heap were freed up in the meantime, getting the same address every time again and again is exactly what I would expect. I'd have to see the remaining code to be sure, though.

==> Your code is just fine. UserDetail d2 has been deallocated just as you asked for.

Upvotes: 0

Martin R
Martin R

Reputation: 539815

d2 is a pointer to the allocated object, so what you want is to log the value of d2, not its address &d2:

NSLog(@"check address::::::> %p", d2); // remove the & !

(&d2 is the address of the local stack variable, and that may be the same for each call.)

Upvotes: 3

mithlesh jha
mithlesh jha

Reputation: 343

If you are in NON-ARC environment, replace your return statement of the function with return [d2 autorelease]. On ARC, you don't need to do anything.

Upvotes: 0

Related Questions