不务正业之OC(三)retain与release

当我们打开ARC自动引用计数时,retainCount不可用,那就关闭吧

1

2

Person.h

#import <Foundation/Foundation.h>
 
@interface Person : NSObject
@end

Person.m

#import "Person.h"
 
@implementation Person
//定义dealloc方法,当对象引用计数为0时,会被调用
- (void)dealloc{
    NSLog(@"Person is dealloc!");
    [super dealloc];
}
@end

main.m

#import <Foundation/Foundation.h>
#import "Person.h"
 
int main(int argc, const char * argv[])
{
 
    @autoreleasepool {
        //alloc 引用计数加1;retainCount方法返回对象引用计数数
        Person *person1 = [[Person alloc] init]; //1
        NSLog(@"person1:%lu",(unsigned long)[person1 retainCount]);
 
        [person1 retain];//2
        NSLog(@"person1:%lu",(unsigned long)[person1 retainCount]);
 
        [person1 release];//1
        NSLog(@"person1:%lu",(unsigned long)[person1 retainCount]);
 
        [person1 release];//0,调用dealloc
    }
    return 0;
}

结果:

2014-04-27 17:16:48.041 Person[10196:303] person1:1
2014-04-27 17:16:48.043 Person[10196:303] person1:2
2014-04-27 17:16:48.043 Person[10196:303] person1:1
2014-04-27 17:16:48.043 Person[10196:303] Person is dealloc!

Post a Comment