Notes for autorelease variables in iOS

Source: Internet
Author: User
Tags variable scope

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.