object reference is same in function calling

后端 未结 3 1544
独厮守ぢ
独厮守ぢ 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.

提交回复
热议问题