iOS中接口与API设计(二)

433 阅读2分钟

这是我参与8月更文挑战的第23天,活动详情查看:8月更文挑战


全能初始化方法

创建对象的时候通过传入一些参数来完成的初始化的方法

来了例子

#import <Foundation/Foundation.h>
@interface Phone : NSObject
@property (nonatomic,copy,readonly) NSString *name;
@property (nonatomic,assign,readonly) NSInteger price;

- (instancetype)initWithName:(NSString *)name withPrice:(NSInteger)price;
@end


#import "Phone.h"
@implementation Phone
- (instancetype)initWithName:(NSString *)name withPrice:(NSInteger)price{
    self = [super init];
    if (self) {  
        _name = [name copy];
        _price = price;
    }
    return self;
}
@end

-(instancetype)initWithName:(NSString *)name withPrice:(NSInteger)price

这个方法就是全能初始化方法,其他的初始化方法都应该调用这个方法来创建对象,所以我们需要在实现init方法,为了避免出现俩个属性值不为空值,这里赋了默认值

#import "Phone.h"
@implementation Phone

- (instancetype)initWithName:(NSString *)name withPrice:(NSInteger)price{
    self = [super init];
    if (self) {  
        _name = [name copy];
        _price = price;
    }
    return self;
}

- (instancetype)init{
    return [self initWithName:@"iPhone" withPrice:999];
}
@end

也可以直接在init方法里抛异常

- (instancetype)init{
    @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"必须使用initWithName: withPrice:方法" userInfo:nil];
}

现有类iPhone继承Phone类,那么.m实现为一下内容

#import "Phone.h"
@interface iPhone : Phone
- (instancetype)initWithName:(NSString *)name;
@end

#import "iPhone.h"
@implementation iPhone
- (instancetype)initWithName:(NSString *)name{
    return [super initWithName:name withPrice:999];
}
- (instancetype)init{
    return [self initWithName:@"iphone7"];
}
@end

describe

Phone *p = [[Phone alloc]initWithName:@"iPhone" withPrice:999];
NSLog(@"%@",p);

log:

<Phone: 0x60400022dd00>

为了方便调试打印更多信息,我们需要在Phone类中重写describe方法

- (NSString *)description{
`return [NSString stringWithFormat:@"<%@:%p \"%@\">", [self class],self,
            @{@"_name":_name,
              @"_price":@(_price)
              }];
}

Phone *p = [[Phone alloc]initWithName:@"iPhone" withPrice:999];
NSLog(@"%@",p);

log:

<Phone:0x600000238ae0 "{
    "_name" = iPhone;
    "_price" = 999;
}">

debugDescribe

debugDescribe方法主要是开发者在调试器中以控制台命令"po"打出对象时才调用,在debugDescribe方法里可以添加你认为调试必要的一些内容

  • 在此处打断点,没有重写debugDescribe方法 demo

    使用po在控制台输出log: 没有重写debugDescription

  • 重写debugDescribe方法

    - (NSString *)debugDescription{
        return [NSString stringWithFormat:@"<%@: %p> %@", [self class], self,
                @{@"_name":_name,
                  @"_price":@(_price),
                  @"more info":@"XXXXX"
                  }];
    }
    

    使用po在控制台输出log: 重写debugDescription


关于iOS接口与API设计相关知识点