OC中Property参数解析|青训营笔记

133 阅读3分钟

OC中Property参数解析|青训营笔记

这是我参与「第四届青训营 」笔记创作活动的第1天

OC类

任何的类,最终都会继承于NSObject

这里基于Foundation框架的解析

这是一个Person类的定义

@interface Person : NSObect

@end

当然里面可能会有很多很多属性

开发中常见的就是使用Property去描述参数

nonatomic & atomic

对于一个类来熟,最基本的就是nonatomic

nonatomic : 属于不安全的,不需要加锁,读取非常快

atomic : 属于安全的,加锁,常用于本地缓存

不书写此关键字则默认为atomic,而开发中常用nonatomic

@interface Person : NSObect

@property (nonatomic) NSIntager age;
  
@end

strong & copy

上面说了一个普通的C语言存储属性,接下来介绍OC存储

这里写了一个不可变的name属性

在OC中,所有的不可变属性均应采用copy的参数

而我们可变的属性则采取strong

@interface Person : NSObect

@property (nonatomic) NSIntager age;
  
@property (nonatomic, copy) NSString *name;

@property (nonatomic, strong) NSMutableArray *things;

@end

copy是基于strong的一种参数,只不过会在被修改的时候,复制一份给外界使用

nullable & nonnull

平时我们是不用关心是否为空,通常也会采用计算属性

在封装与基础建设中,我们有时也会考虑是否加上

@interface Person : NSObect

@property (nonatomic) NSIntager age;
  
@property (nonatomic, copy) NSString *name;

@property (nonatomic, strong) NSMutableArray *things;

@property (nonatomic, copy, nullable) NSString *car;

@property (nonatomic, copy, nonnull) NSString *token;

@end

这里,声明Person对象有可能没有车,存储值时需要根据需求设置

而每个Person都拥有唯一的token,可以是手动设置等等操作

readonly & readwrite

默认所有的属性都为readwrite,意思是可读可写

而readonly作为只读常用于单例对象等

这里先讨论以存储属性的角度,readonly默认为strong

明显上面的token可以只读,我们改一下代码

@interface Person : NSObect

@property (nonatomic) NSIntager age;
  
@property (nonatomic, copy) NSString *name;

@property (nonatomic, strong) NSMutableArray *things;

@property (nonatomic, copy, nullable) NSString *car;

@property (nonatomic, readonly, nonnull) NSString *token;

@end

其实可以想一想,token是否可以作为计算属性呢?

null_resettable

这个没有可以类比的关键字,常用于在UI上的封装

这个关键字不可以用于计算属性

表示改类会重写setter或getter方法,让程序根据这个属性进行变化

必须且只能重写setter或getter中的其中一个

这里不上代码,会在之后讲解UI封装的时候再次提及

计算属性

上述的所有关键字其实无非都是在生成getter和setter方法

存储属性会占用内存,而计算属性不会占用内存

实现关键字对应的getter或/和setter方法,便可以

这里放一段代码,来理解一个计算属性

@interface Weather : NSObject

/// 时间
@property (nonatomic, copy) NSString *currentTime;

/// 时间(计算属性)
@property (nonatomic, readonly) NSDate *currentDate;

@end
@implementation Weather
  
- (void)setCurrentTime:(NSString *)currentTime {
    _currentTime = currentTime;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"YYYY-MM-DD'T'HH:mm:ss'Z'";
    _currentDate = [formatter dateFromString:currentTime];
}

@end