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;
问题:
[p release]后还能继续访问为什么不报错?
看建议是release后最好不要继续访问。 如果能访问,什么情况下会出问题?
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):
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: