標籤:io ar sp on 2014 log bs cti as
//// 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 deallocedProgram ended with exit code: 0
發現沒有記憶體流失了。
objective-c計數器學習