// // Book.h // obj-c学习1 // // Created by itfanr on 14/11/30. // Copyright (c) 2014年 itfanr. All rights reserved. // #import <Foundation/Foundation.h> @interface Book : NSObject @property float price ; -(id)initWithPrice:(float) price ; @end
//
// Book.m
// obj-c学习1
//
// Created by itfanr on 14/11/30.
// Copyright (c) 2014年 itfanr. All rights reserved.
//
#import "Book.h"
@implementation Book
@synthesize price = _price ;
-(id)initWithPrice:(float)price{
self = [super init] ;
_price = price ;
return self ;
}
- (void)dealloc
{
NSLog(@"book is dealloced!") ;
[super dealloc] ;
}
@end
// // Person.h // obj-c学习1 // // Created by itfanr on 14/11/30. // Copyright (c) 2014年 itfanr. All rights reserved. // #import <Foundation/Foundation.h> #import "Book.h" @interface Person : NSObject @property Book *book ; @property int age ; -(id)initWithAge:(int)age ; @end
//
// Person.m
// obj-c学习1
//
// Created by itfanr on 14/11/30.
// Copyright (c) 2014年 itfanr. All rights reserved.
//
#import "Person.h"
#import "Book.h"
@implementation Person:NSObject
@synthesize book = _book ;
-(void)setBook:(Book *)book{
if(_book != book){
[_book release] ;
_book = [book retain] ;
}
}
-(Book *)book{
return _book ;
}
#pragma mark 初始化
-(id)initWithAge:(int)age {
self = [super init] ;
_age = age ;
return self;
}
#pragma mark 销毁函数 复写
- (void)dealloc
{ [_book release] ;
NSLog(@"Person is dealloced" );
[super dealloc] ;
}
@end
//
// main.m
// obj-c学习1
//
// Created by itfanr on 14/11/29.
// Copyright (c) 2014年 itfanr. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Person.h"
#import "Book.h"
int main(int argc, const char * argv[]) {
Book *book1 = [[Book alloc]initWithPrice:4.5] ;
Person * p = [[Person alloc] initWithAge:18] ;
p.book = book1 ;
[book1 release] ;
[p release] ;
return 0;
}
输出结果是:
2014-11-30 22:38:11.427 obj-c学习1[1228:911238] book is dealloced! 2014-11-30 22:38:11.428 obj-c学习1[1228:911238] Person is dealloced Program ended with exit code: 0
发现没有内存泄漏了。
原文:http://my.oschina.net/itfanr/blog/350636