接口与API设计--16:全能初始化方法

2023-11-22 08:21:39 浏览数 (1)

全能初始化方法

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

来了例子

代码语言:javascript复制
#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方法,为了避免出现俩个属性值不为空值,这里赋了默认值

代码语言:javascript复制
#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方法里抛异常

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

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

代码语言:javascript复制
#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

参考

Effective Objective-C 2.0 编写高质量iOS与OS X代码的52个有效方法

0 人点赞