During iOS development, developers who transfer data from C/C ++ must pay attention to the autorelease variable scope issue in obj-c.
If there is a class under www.2cto.com;
@ Interface ViewController: UIViewController
{
NSDate * memberDate;
NSDate * properDate;
}
@ Property (nonatomic, retain) NSDate * properDate;
@ End
@ Interface ViewController: UIViewController
{
NSDate * memberDate;
NSDate * properDate;
}
@ Property (nonatomic, retain) NSDate * properDate;
@ End
Then initialize the member variables in the class implementation:
-(Void) viewDidLoad
{
[Super viewDidLoad];
MemberDate = [NSDate date];
Self. properDate = [NSDate date];
}
-(Void) viewDidLoad
{
[Super viewDidLoad];
MemberDate = [NSDate date];
Self. properDate = [NSDate date];
}
Use these two member variables in the class member method, such as [memberDate description]. In this case, the value of memberDate is invalid, and the value of properDate is valid. Why?
Because memberDate = [NSDate date]; after this statement is executed, memberDate points to an autorelease variable. These autorelease variables will be release during the next round-robin of runloop. Therefore, memberDate is the wild pointer in c/c ++, And the wild pointer will cause the program to crash. Property is declared with retain, so the address retrain count pointed to by the member variable properDate is 1 and will not be auto release, so it is a valid memory space and of course it won't crash.
Lessons learned: autorelease variables should be used in the scope unless you manually retrain. For example, the code above can change memberDate = [[NSDate date] retrain]; in this way, memberDate points to the same address as the class life cycle. The retrain count is 1 and will not be autorelisted. However, in the dealloc method, you must manually [memberDate release] or there will be a memory overflow.
From happy Program