new方法的實現原理,new方法實現原理
//// main.m// 04-new方法的實現原理#import <Foundation/Foundation.h>#import "Person.h"#import "Student.h"int main(int argc, const char * argv[]) { /* Person * p = [[Person alloc] init]; [p run]; Person * p1 = [Person new]; [p1 run]; Person * p2 = [Person person]; [p2 run]; Student * stu = [Student new]; [stu sleep]; // Dog *dog = [[Animal alloc]init ]; Student * stu2 = [Student person]; [stu2 sleep]; */ // Person * person = [[Person alloc] initWithName:@"笑著"]; /* Person * per = [Person personWithName:@"xiaozhe"]; [per run]; NSLog(@"%@",per); Student * stu = [Student personWithName:@"奶茶"]; [stu sleep]; NSLog(@"%@",stu); */ // NSString * str = [NSString string] // NSArray * array = [NSArray arraywi] Student * stu = [Student studetWithName:@"笑著"]; [stu sleep]; NSLog(@"%@",stu); return 0;}
#import <Foundation/Foundation.h>@interface Person : NSObject@property NSString * name;@property int age;- (id)initWithName:(NSString *)name;- (void)run;+(id)person;+(id)personWithAge:(int)age;+(id)personWithName:(NSString *)name;+(id)personWithName:(NSString *)name andAge:(int)age;@end
#import "Person.h"@implementation Person- (id)initWithName:(NSString *)name{ if (self = [super init]) { _name = name; } return self;}+(id)person{//// Person * p = [[Person alloc] init]; //誰調用,他就代表誰 Person * p = [[self alloc] init]; //[[Person alloc] init] //[[Sutdent alloc] init] return p;}+(id)personWithName:(NSString *)name{ /* Person * person = [[self alloc] initWithName:name]; return person; */ Person * person = [self person]; person.name = name; return person; }- (void)run{ NSLog(@"人跑起來了");}- (NSString *)description{ return [NSString stringWithFormat:@"name %@", _name];}@end
#import "Person.h"@interface Student : Person- (void)sleep;+(id)studet;+(id)studetWithName:(NSString *)name;@end
#import "Student.h"@implementation Student+(id)studet{ return [self person];}+(id)studetWithName:(NSString *)name{ return [self personWithName:name];}- (void)sleep{ NSLog(@"就愛睡");}@end
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。