Skip to content

Commit cd5b9a7

Browse files
committed
[9. @Property中有哪些属性关键字?/ @Property 后面可以有哪些修饰符?]增加自旋锁解释
1 parent 827c381 commit cd5b9a7

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

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

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1058,6 +1058,53 @@ NSObject *foo = [[NSObject alloc] init];
10581058
10591059
3. 不常用的:`nonnull`,`null_resettable`,`nullable`
10601060
1061+
1062+
注意:很多人会认为如果属性具备 nonatomic 特质,则不使用
1063+
“同步锁”。其实在属性设置方法中使用的是自旋锁,自旋锁相关代码如下:
1064+
1065+
1066+
```Objective-C
1067+
static inline void reallySetProperty(id self, SEL _cmd, id newValue, ptrdiff_t offset, bool atomic, bool copy, bool mutableCopy)
1068+
{
1069+
if (offset == 0) {
1070+
object_setClass(self, newValue);
1071+
return;
1072+
}
1073+
1074+
id oldValue;
1075+
id *slot = (id*) ((char*)self + offset);
1076+
1077+
if (copy) {
1078+
newValue = [newValue copyWithZone:nil];
1079+
} else if (mutableCopy) {
1080+
newValue = [newValue mutableCopyWithZone:nil];
1081+
} else {
1082+
if (*slot == newValue) return;
1083+
newValue = objc_retain(newValue);
1084+
}
1085+
1086+
if (!atomic) {
1087+
oldValue = *slot;
1088+
*slot = newValue;
1089+
} else {
1090+
spinlock_t& slotlock = PropertyLocks[slot];
1091+
slotlock.lock();
1092+
oldValue = *slot;
1093+
*slot = newValue;
1094+
slotlock.unlock();
1095+
}
1096+
1097+
objc_release(oldValue);
1098+
}
1099+
1100+
void objc_setProperty(id self, SEL _cmd, ptrdiff_t offset, id newValue, BOOL atomic, signed char shouldCopy)
1101+
{
1102+
bool copy = (shouldCopy && shouldCopy != MUTABLE_COPY);
1103+
bool mutableCopy = (shouldCopy == MUTABLE_COPY);
1104+
reallySetProperty(self, _cmd, newValue, offset, atomic, copy, mutableCopy);
1105+
}
1106+
```
1107+
10611108
###10. weak属性需要在dealloc中置nil么?
10621109
不需要。
10631110

0 commit comments

Comments
 (0)