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;
}



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