———————————————————————————————————————————
Multiple object memory management (wild pointers & memory leaks)
(Note: This part of the knowledge should be combined with "single object memory Management" to understand)
This part of the knowledge is relatively simple, it involves a situation that will produce a wild pointer and how to avoid the memory leak problem.
Code:
#import <Foundation/Foundation.h>
@interface Car:nsobject
-(void) run;
@end
@implementation Car
Monitor car object has not been released
-(void) dealloc
{
NSLog (@ "Car dealloc!");
[Super Dealloc];
}
-(void) run
{
NSLog (@ "Car run!");
}
@end
@interface Person:nsobject
{
Car *_car;
}
-(void) driver;
-(void) Setcar: (car *) car;
@end
@implementation person
-(void) dealloc
{
[_car Release];//_car and car point to the same piece of memory space, so it is possible to execute any command that frees memory in either of these two.
NSLog (@ "Person dealloc!");
[Super Dealloc];
}
-(void) driver
{
[_car Run];
}
-(void) Setcar: (Car *) car
{
[Car retain];
_car=car;
}
@end
int main (int argc, const char * argv[]) {
@autoreleasepool {
Person *p=[person new];//p 1
Car *car=[car New];//car 1
[P Setcar:car];//car 2
P.car=car; This is the same as above, because we write the set method, so we can write some syntax.
[Car release];//at this time car release 1
[P driver];//p Call driver method, which will use the car this instance variable to call the Run method, but car has been released before, changed to a wild pointer, so that will be error, then what should be handled? Obviously we can retain the car object in the Setcar method before releasing the car, so that when car finishes executing the Set method, the count becomes 2. However, this will not be an error, but the car count has become 1, if not properly operated, there will be a memory leak. So this method is only temporary. But this sentence can now be executed without error.
[P release];//we add a [car release] in the Dealloc method of P; Let the car's memory free so that there is no memory leak. At this point the P-count is 0 for the 0,car count.
}
return 0;
}
———————————————————————————————————————————
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Objective-c "Multiple object memory management (wild pointers & memory leaks)"