1. 程式人生 > >oc35--自定義構造方法

oc35--自定義構造方法

type code port pro return ini 自定義構造方法 argc main

//
//  Person.h

#import <Foundation/Foundation.h>

@interface Person : NSObject

@property int age;
@property NSString *name;

/*
 自定義構造方法:
 其實就是自定義一個init方法
 1.一定是對象方法
 2.一定返回id/instancetype
 3.方法名稱一定以init開頭
*/
- (instancetype)initHwwAge:(int)age;

// 一個類可以有0個或者多個自定義構造方法
- (instancetype)initWithName:(NSString *)name;

// 自定義構造方法可以有1個或多個參數 - (instancetype)initWithAge:(int)age andName:(NSString *)name; @end
//
//  Person.m

#import "Person.h"

@implementation Person

- (instancetype)init
{
    if (self = [super init]) {
        _age = 10;
    }
    return self;
}

- (NSString *)description
{
    return [NSString stringWithFormat:@"
age = %i, name = %@", _age, _name]; } - (instancetype)initHwwAge:(int)age { if (self = [super init]) { _age = age; } return self; } - (instancetype)initWithName:(NSString *)name { if (self =[super init]) { _name = name; } return self; } - (instancetype)initWithAge:(int
)age andName:(NSString *)name { if (self = [super init]) { _age = age; _name = name; } return self; } @end
//
//  main.m
//  自定義構造方法

#import <Foundation/Foundation.h>
#import "Person.h"

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

    Person *p9 = [Person new];//_age=10,_name=nil
    Person *p8 = [[Person alloc] init];
    p8.age = 20;//_age=10,_name=nil
    Person *p7 = [[Person alloc] initHwwAge:20];//_age=20,_name=nil
    Person *p6 = [[Person alloc] initWithName:@"lnj"];//_age=0,_name=@"lnj"
    Person *p5 = [[Person alloc] initWithAge:20 andName:@"lnj"];//_age=20,_name=@"lnj"
    NSLog(@"%@", p5);
    
    Person *p4 = [[Person alloc] init];
    p4.age = 30;//_age=30,_name=nil
    Person *p3 = [[Person alloc] initHwwAge:30];//_age=30,_name=nil
    Person *p23 = [[Person alloc] initWithName:@"lmj"];//_age=0,_name=@"lmj"
    Person *p2 = [[Person alloc] initWithAge:30 andName:@"lmj"];//_age=30,_name=@"lmj"
    NSLog(@"%@", p2);
    return 0;
}

oc35--自定義構造方法