Student.h:
#import <Foundation/Foundation.h> @interface Student : NSObject @property int age; //默認會生成一個_age屬性 @end
Student.m:
#import "Student.h" @implementation Student //@synthesize age=_age;//xcode4.5中可以不使用synthesise方法,直接在頭文件中使用property方法即可 //如果只在m文件中定義而沒有在h文件中申明的方法屬于privte方法,如果不寫類型一般默認是protected方法 -(void)dealloc{ //構造父類的回收方法 NSLog(@"%@被銷毀了",self); NSLog(@"_age %i",_age); [super dealloc];//一定要調用super的dealloc方法,最好放在最后面調用 } @end
main:
#import <Foundation/Foundation.h> #import "Student.h" int main(int argc, const char * argv[]) { @autoreleasepool { Student *stu=[[[Student alloc] init] autorelease]; //alloc方法計數器為1 [stu retain];//調用一次retain方法計數器加1 NSLog(@"retaincount is %zi",[stu retainCount]); [stu release];//調用一次release方法計數器減1 NSLog(@"retaincount is %zi",[stu retainCount]); stu.age=10; [stu retain];//add 1 //這兒retainCount返回的是Unsigned long 無符號長整形 %z代表無符號 NSLog(@"retaincount is %zi",[stu retainCount]); NSLog(@"Student age is %i",[stu age]); [stu release]; //計數器為0就調用dealloc方法 } return 0; }
結果:
2013-08-02 14:57:25.342?內存管理1retain和release[788:303] retaincount is 2
2013-08-02 14:57:25.344?內存管理1retain和release[788:303] retaincount is 1
2013-08-02 14:57:25.344?內存管理1retain和release[788:303] retaincount is 2
2013-08-02 14:57:25.344?內存管理1retain和release[788:303] Student age is 10
2013-08-02 14:57:25.345?內存管理1retain和release[788:303] <Student: 0x100109a90>被銷毀了
2013-08-02 14:57:25.345?內存管理1retain和release[788:303] _age 10
本文轉自蓬萊仙羽51CTO博客,原文鏈接:http://blog.51cto.com/dingxiaowei/1366576,如需轉載請自行聯系原作者