objective-c - Ojbect-c对象release后还能访问其变量?
大家讲道理
大家讲道理 2017-05-02 09:24:08
0
1
578

1、在关闭ARC的情况下,为什么一个Object-c对象主动release后,其成员变量还能继续访问?
代码如下:

@interface person : NSObject

@property int a;

@end

@implementation person

@synthesize a;

- (void) dealloc
{
    NSLog(@"dealloc person");
}

@end

int main()
{
    person* p = [[person alloc]init];
    p.a = 10;
    NSLog(@"%d", p.a);   //10
    [p release];         // dealloc
    p.a=20;
    NSLog(@"%d", p.a);   //20  
    return 0;
}

问题:
在调用[p release];后,还能继续访问p的变量a;

问题:

  1. [p release]后还能继续访问为什么不报错?

  2. 看建议是release后最好不要继续访问。 如果能访问,什么情况下会出问题?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(1)
Peter_Zhu

Because the address pointed to by p has not changed after release, if the operating system has not reclaimed that piece of memory, no error will be reported if you continue to access it, which is a dangling pointer.


p ----------------------------------> Person {a: 10, reference_count: 1}

p -- send release message to --> Person {a: 10, reference_count: 1}

p ----------------------------------> Person {a: 10, reference_count: 0} (dealloced )

p --------- get value of a --------> Person {a: 10, reference_count: 0} (a is still 10)


As mentioned above, if you want it to cause problems, just keep trying until the operating system stops it (usually very quickly):

person* p = [[person alloc]init];
p.a = 10;
NSLog(@"%d", p.a);
[p release];

do {
    NSLog(@"%d", p.a);
} while (TRUE);

Execute it a few times and you will see that there is no pattern at all when it hangs. . . So it’s not that it’s best not to continue visiting, it’s definitely not to continue visiting. . .


I didn’t see it just now, dealloc also needs to be modified:

- (void) dealloc
{
    NSLog(@"dealloc person");
    
    [super dealloc]; // 一定要有
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template