前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >接口与API设计--18:尽量使用不可变对象

接口与API设计--18:尽量使用不可变对象

作者头像
xy_ss
发布2023-11-22 08:22:40
1370
发布2023-11-22 08:22:40
举报
文章被收录于专栏:浮躁的喧嚣
  • 使用属性时,可将其声明为“readonly”(默认:readwrite)
  • 比如通过初始化方法传入的属性,那么单独声明的属性值就可以声明为readonly
代码语言: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
  • 如果想修改数据,且不想让外人知道,通常可以在对象内部分类中将其设置为readwrite
代码语言:javascript
复制
#import "Phone.h"
//分类中重新声明
@interface Phone()
@property (nonatomic,copy,readwrite) NSString *name;
@property (nonatomic,assign,readwrite) NSInteger price;
@end

@implementation Phone
- (instancetype)initWithName:(NSString *)name withPrice:(NSInteger)price{
    self = [super init];
    if (self) {
        
        _name = [name copy];
        _price = price;
    }
    return self;
}
@end
  • 尽量不要把可变的array、set、dictionary等作为公开属性,应该提供相应的方法,以此修改对象中的可变属性 为什么不能直接把phoneArray定义成可变的,通过phoneArray来控制? 比如在添加或者删除时,Phone对象可能要执行其他相关操作,如果直接从底层修改了内部用于存储的phoneArray,在Phone对象不知情时,直接修改phoneArray可能会让对象间各数据不一致
代码语言:javascript
复制
#import <Foundation/Foundation.h>
@interface Phone : NSObject
@property (nonatomic,copy,readonly) NSString *name;
@property (nonatomic,assign,readonly) NSInteger price;
@property (nonatomic,strong,readonly) NSArray *phoneArray;

- (instancetype)initWithName:(NSString *)name withPrice:(NSInteger)price;
- (void)addPhone:(Phone *)phone;
- (void)removePhone:(Phone *)phone;
@end

#import "Phone.h"
@interface Phone()
@property (nonatomic,copy,readwrite) NSString *name;
@property (nonatomic,assign,readwrite) NSInteger price;
@property (nonatomic,strong,readwrite) NSMutableArray *savePhoneArray;
@end

@implementation Phone

- (instancetype)initWithName:(NSString *)name withPrice:(NSInteger)price{
    self = [super init];
    if (self) {
        _name = [name copy];
        _price = price;
        _savePhoneArray = [[NSMutableArray alloc]init];
    }
    return self;
}
- (instancetype)init{
    return [self initWithName:@"iPhone" withPrice:999];
}
-(NSMutableArray *)savePhoneArray{
    if (_savePhoneArray == nil) {
        _savePhoneArray = [NSMutableArray new];
    }
    return _savePhoneArray;
}

- (void)addPhone:(Phone *)phone{
    [self.savePhoneArray addObject:phone];
}
- (NSArray *)phoneArray{
    return [self.savePhoneArray copy];
}
- (void)removePhone:(Phone *)phone{
    [self.savePhoneArray removeObject:phone];
}
@end

参考

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-07-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 参考
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档