ARC是cocoa系统帮你完成对象内存释放的引用计数机制
.h文件
// Person.h
// 01-ARC
//
// Created by ma c on 15/8/13.
// Copyright (c) 2015年. All rights reserved.
// #import <Foundation/Foundation.h> @interface Person : NSObject
@property(nonatomic,strong)NSString *name;
@property(nonatomic,assign)NSInteger age;
+(Person*)personWithName:(NSString*) name andAge:(NSInteger) age;
-(id)initWithName:(NSString*) name andAge:(NSInteger) age;
-(void)show;
@end
.m文件
// Person.m
// 01-ARC
//
// Created by ma c on 15/8/13.
// Copyright (c) 2015年. All rights reserved.
// #import "Person.h" @implementation Person
-(id)initWithName:(NSString*) name andAge:(NSInteger) age
{
self = [super init];
if(self)
{
_name = name;
_age = age;
}
return self;
} /*
在类方法中,由于没有创建对象实例,所以:self指针不能用,实例变量不能用。
*/
+(Person*)personWithName:(NSString*) name andAge:(NSInteger) age
{
return [[Person alloc]initWithName:name andAge:age];
} -(void)show
{
NSLog(@"name:%@,age:%ld",_name,_age);
} /*
创建对象时是先创建父类的部分,再创建子类的部分;
销毁对象时,顺序正好相反
ARC禁止显式的发送dealloc消息
*/
-(void)dealloc
{
NSLog(@"person dealloc");
//[super dealloc]; //禁止显式的发送dealloc消息
}
@end
主函数测试
// main.m
// 01-ARC
//
// Created by ma c on 15/8/13.
// Copyright (c) 2015年. All rights reserved.
// #import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[])
{
@autoreleasepool
{
Person *person = [[Person alloc]initWithName:@"Jim" andAge:]; [person show];
//[person dealloc];//error,底层会自动调用该方法用来销毁对象
}
return ;
}
测试结果:
-- ::54.904 -ARC[:] name:Jim,age:
-- ::54.905 -ARC[:] person dealloc
Program ended with exit code: