首页 > 代码库 > 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



new方法的实现原理