您的位置:首页 > 其它

对象的动态和静态构造创建的区别

2013-07-29 12:38 176 查看
Student.h:

#import <Foundation/Foundation.h>

@interface Student : NSObject

@property(nonatomic,retain) NSString * name;

@property(nonatomic,assign) int age;

@end

Student.m:
#import "Student.h"
@implementation Student
//动态方法,在main函数中类alloc了之后调用,但是要手动管理内存,要手动释放
-(id) initWithAge:(int)age{
if (self == [super init]) {
_age = age;
}
return self;
}

//静态构造方法,在main函数中不需要你手动管理内存释放
+(id)studentWithAge:(int)age{
Student *stu = [[[Student alloc] init] autorelease];\
stu.age = age;
return stu;
}

-(NSString *)description{
return [NSString stringWithFormat:@"name:%@ age:%i创建了",_name,_age];
}

-(void)dealloc{
NSLog(@"name:%@ age:%i被释放了",_name,_age);
[_name release];
[super dealloc];
}
@end

main:
#import <Foundation/Foundation.h>
#import "Student.h"

int main(int argc, const char * argv[])

{
@autoreleasepool {

//动态方法需要手动释放内存

Student *stu1= [[Student alloc] initWithAge:10];

stu1.name = @"dingxiaowei";

NSLog(@"%@",stu1);

[stu1 release];

//静态构造方法不需要你管理内存

Student *stu2 =[Student studentWithAge:20];

stu2.name = @"wangning";

NSLog(@"%@",stu2);

}

return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐