1. When ARC is turned off, why can its member variables continue to be accessed after an Object-c object is actively released?
The code is as follows:
@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;
}
Problem:
After calling [p release];, you can still access the variable a of p;
Question:
Why can I continue to access it after [p release] and why no error is reported?
The suggestion is that it is best not to continue accessing after release. If you can access it, under what circumstances will something go wrong?
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: