Objective-c - Can the variables of an Objective-c object be accessed after it is released?
大家讲道理
大家讲道理 2017-05-02 09:24:08
0
1
608

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:

  1. Why can I continue to access it after [p release] and why no error is reported?

  2. 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?

大家讲道理
大家讲道理

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

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