- 使用属性时,可将其声明为“readonly”(默认:readwrite)
- 比如通过初始化方法传入的属性,那么单独声明的属性值就可以声明为readonly
#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
#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可能会让对象间各数据不一致
#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个有效方法