object reference is same in function calling

后端 未结 3 1543
独厮守ぢ
独厮守ぢ 2021-01-26 01:06
 -(UserDetail *)functionCheck :(NSString *)str
 {
    UserDetail *d2=[[UserDetail alloc] init];
    NSLog(@\"check address::::::> %p\",&d2);
    d2.auth_token=str         


        
相关标签:
3条回答
  • 2021-01-26 01:49

    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.

    0 讨论(0)
  • 2021-01-26 01:59

    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.

    0 讨论(0)
  • 2021-01-26 02:06

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

    0 讨论(0)
提交回复
热议问题