object reference is same in function calling

丶灬走出姿态 提交于 2019-12-02 14:58:14

问题


 -(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.


回答1:


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.)




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/23653972/object-reference-is-same-in-function-calling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!