Ben*_*ynn 4 objective-c nsnumber mutability
这是一个错误还是这里有一个微妙的教训?
NSNumber *someNumber = @(1);
[someNumber respondsToSelector:@selector(mutableCopy)]; // returns YES (!)
[someNumber respondsToSelector:@selector(mutableCopyWithZone:)]; // returns NO
Run Code Online (Sandbox Code Playgroud)
Apple LLVM 7.1(iOS SDK 9.3)
这是因为NSObject它本身通过调用-mutableCopy来实现(对于所有对象,甚至那些不符合NSCopying或者的对象NSMutableCopying)-mutableCopyWithZone:(这样实现的东西NSMutableCopying只需实现-mutableCopyWithZone:而无需重复实现-mutableCopy).
继承的所有内容都会NSObject响应-mutableCopy,但如果您实际调用它,它会因为NSNumber没有响应而崩溃-mutableCopyWithZone:.
你可以看到这个
assert([NSObject instanceMethodForSelector:@selector(mutableCopy)] == [NSNumber instanceMethodForSelector:@selector(mutableCopy)])
Run Code Online (Sandbox Code Playgroud)
bbum的分析很好地总结了这一点 - 在动态执行这些检查时会有一些微妙的边缘情况,因为您可能得到的答案根本不是您所期望的.
| 归档时间: |
|
| 查看次数: |
91 次 |
| 最近记录: |