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

全能初始化方法

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

来了例子

#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

参考

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 所有对象均要初始化。在初始化时,有些对象可能无须开发者向其提供额外信息,不过一般来说还是要提供的。通常情况下,对象...
    CoderCurtis阅读 358评论 0 1
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,145评论 1 32
  • 很多父母以为,只要让孩子在幼儿园的最后一年上个学前班,提前学点简单数学运算,就能帮助他们学好小学数学,然而真正的数...
    4314f3faf886阅读 12,308评论 0 7
  • 我已经记不起和这一群人的相遇是什么样的场景了。再回首时,对于那些以往,已是刻骨铭心。记不清开始,只记得过程,忽略了...
    蔡建斌阅读 214评论 0 0
  • 竟如前有一堵墙般, 想打破而几度踉跄, 话说出却被弹回得四处飞散, 粘结它们的只是 战胜的欲望。
    一朵雪花阅读 184评论 0 0