oc-the code in the. h files and. m files in memory management, comments are important

Source: Internet
Author: User

. h file

-----------------------------------------

#import <Foundation/Foundation.h>

#import "Car.h"

@interface Person:nsobject

{

Car *_car;

NSString *_name;

}

-(void) SetName: (NSString *) name;

-(NSString *) name;

-(void) Setcar: (car *) car;

-(car *) car;

-(void) drive;

@end

. m file

-----------------------------------------

#import "Person.h"

@implementation person

-(void) SetName: (NSString *) name{

if (_name!=name) {

Release old value

[_name release];

Retain new value

_name=[name retain];

}

}

-(NSString *) name{

return _name;

}

-(void) Setcar: (Car *) car{

if (_car!=car) {//With this is afraid to pass in the same C1 two times, it will be a wild pointer error

C1=2->c1=1

[_car release];//when the first time C1 came in, because there was no car before, so _car=nil. [Nil release] execution does not error, but also invalid *//When C2 passed in, C1 before the main function has been release once, C1 has been 1, and the current _car is C1, so C2 in time, C1 (_car) release, Retaincount=0, automatic call dealloc destroy, [old value release]

C1 =2->c2=2

_car=[car retain];//When the first C1 came in, c1=1+1=2, when C2 passed in, C2 from 1 to 2, exit, return to main function

}

}

-(Car *) car{

return _car;

}

-(void) drive{

[_car Run];

}

-(NSString *) description{

//

return [NSString stringwithformat:@ "Age is%d", _age];

//}

-(void) dealloc{

Now it's C2, c2=0.

[_car RELEASE];//C2 has been passed in, ("At this time Car" =_car), at this time the _car again release, also destroyed to

[_name release];

NSLog (@ "Person object is destroyed!) "); Print 4:person object is destroyed!

[Super Dealloc];

}

@end

oc-the code in the. h files and. m files in memory management, comments are important

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.