Skip to content

Commit c799263

Browse files
committed
setter=<name>的使用场景进行说明【9. @Property中有哪些属性关键字?/ @Property 后面可以有哪些修饰符?
1 parent 4f91a20 commit c799263

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

01《招聘一个靠谱的iOS》面试题参考答案/《招聘一个靠谱的iOS》面试题参考答案(上).md

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -982,8 +982,35 @@ NSObject *foo = [[NSObject alloc] init];
982982
983983
`getter=<name>`的样式:
984984
985+
986+
```Objective-C
985987
@property (nonatomic, getter=isOn) BOOL on;
986-
( `setter=<name>`这种不常用,也不推荐使用。故不在这里给出写法。)
988+
```
989+
<p><del>( `setter=<name>`这种不常用,也不推荐使用。故不在这里给出写法。)
990+
</del></p>
991+
992+
993+
`setter=<name>`一般用在特殊的情境下,比如:
994+
995+
996+
在数据反序列化、转模型的过程中,服务器返回的字段如果以 `init` 开头,所以你需要定义一个 `init` 开头的属性,但默认生成的 `setter``getter` 方法也会以 `init` 开头,而编译器会把所有以 `init` 开头的方法当成初始化方法,而初始化方法只能返回 self 类型,因此编译器会报错。
997+
998+
这时你就可以使用下面的方式来避免编译器报错:
999+
1000+
1001+
```Objective-C
1002+
@property(nonatomic, strong, getter=p_initBy, setter=setP_initBy:)NSString *initBy;
1003+
1004+
```
1005+
1006+
1007+
另外也可以用关键字进行特殊说明,来避免编译器报错:
1008+
1009+
```Objective-C
1010+
@property(nonatomic, readwrite, copy, null_resettable) NSString *initBy;
1011+
- (NSString *)initBy __attribute__((objc_method_family(none)));
1012+
```
1013+
9871014
3. 不常用的:`nonnull`,`null_resettable`,`nullable`
9881015
9891016
###10. weak属性需要在dealloc中置nil么?

0 commit comments

Comments
 (0)