07-10、自定义构造方法 - (instancetype)in

2017-09-22  本文已影响0人  山中石头

如何自定义构造方法

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

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

//    Person *p = [Person new];
//    Person *p = [[Person alloc] init];
//    p.age = 20;
//    Person *p = [[Person alloc] initWithAge:20];
//    Person *p = [[Person alloc] initWithName:@"lnj"];
Person *p = [[Person alloc] initWithAge:20 andName:@"lnj"];
NSLog(@"%@", p);

//    Person *p2 = [[Person alloc] init];
//    p2.age = 30;
//    Person *p2 = [[Person alloc] initWithAge:30];
//    Person *p2 = [[Person alloc] initWithName:@"lmj"];
Person *p2 = [[Person alloc] initWithAge:30 andName:@"lmj"];
NSLog(@"%@", p2);
return 0;
}
Person.h
#import <Foundation/Foundation.h>

@interface Person : NSObject

@property int age;
@property NSString *name;

/*
 自定义构造方法:
 其实就是自定义一个init方法
 1.一定是对象方法
 2.一定返回id/instancetype
 3.方法名称一定以init开头
*/
- (instancetype)initWithAge:(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)initWithAge:(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

自定义构造方法在继承中的表现

Student.h
#import "Person.h"

@interface Student : Person

@property int no; // 学号

- (instancetype)initWithAge:(int)age andName:(NSString *)name andNo:(int)no;
@end
Student.m
#import "Student.h"

@implementation Student

- (instancetype)initWithAge:(int)age andName:(NSString *)name andNo:(int)no
{
   /*
if (self = [super init]) {
//        _age = age;
    // 狗拿耗子, 多管闲事
    // 自己的事情自己做,所以在这里不要去访问父类中的age和name
    [self setAge:age];
    [self setName:name];
}
 */
if (self = [super initWithAge:age andName:name]) {
    _no = no;
}
return self;
}

- (NSString *)description
{
return [NSString stringWithFormat:@"age = %i, name = %@, no = %i", [self age], [self name], _no];
}
@end

自定义构造方法注意点

注意: 自定义构造方法中的init后面的With的W一定要大写不要小写w这样会报错
//- (instancetype)initwithAge:(int)age

上一篇下一篇

猜你喜欢

热点阅读