Main.m
#import "Person.h"
int main(int argc, const char * argv[])
{
@autoreleasepool
{
/*
通过类方法创建的对象已经加入到自动释放池了
*/
Person *person = [Person personWithName:@"Jack"]; //person:1
//[person autorelease]; 不需要 根据黄金法则
[person showInfo];
//类方法
//NSArray *arrary = [[NSArray alloc] init];
//[arrary release];
NSArray *arrary = [NSArray arrayWithObject:person]; //person:2
//NSString *string1 = [NSString stringWithFormat:<#(NSString *), ...#>]
//NSString *string2 = [NSString stringWithString:<#(NSString *)#>]
//新语法
NSArray *arrary2 = @[@1,@2,@3];
//等价于:
//NSArray *arrary2 = [NSArray arrayWithObjects:@1,@2,@3, nil];
NSNumber *number = @12;
//等价于:
//NSNumber *number = [NSNumber numberWithInt:12];
}
return 0;
}
Person.h
@interface Person : NSObject {
NSString *_name;
}
@property(nonatomic, copy)NSString *name;
//NSArray *arrary = [NSArray arrayWithContentsOfFile:<#(NSString *)#>]
//自定义类方法创建对象
+ (id)personWithName:(NSString *)name;
- (void)showInfo;
Person.m
- (void)dealloc
{
NSLog(@"person dealloc");
[_name release];
[super dealloc];
}
- (void)showInfo {
NSLog(@"name:%@",_name);
}
//自定义类方法创建对象
+ (id)personWithName:(NSString *)name {
Person *person = [[Person alloc] init];
person.name = name;
// [person release]; 错误
return [person autorelease];
}