Does NSNumber respond positively to mutableCopy?

Is this a mistake or is there a subtle lesson here?

NSNumber *someNumber = @(1);
[someNumber respondsToSelector:@selector(mutableCopy)]; // returns YES (!)
[someNumber respondsToSelector:@selector(mutableCopyWithZone:)]; // returns NO

Apple LLVM 7.1 (iOS SDK 9.3)

+4
source share
2 answers

This is because it NSObjectimplements itself -mutableCopy(for all objects, even those that do not match NSCopyingor NSMutableCopying), calling in -mutableCopyWithZone:(so that things implementing NSMutableCopyingwill get just done -mutableCopyWithZone:without repeating the implementation for -mutableCopy).

Everything that inherits from NSObjectanswers to -mutableCopy, but if you actually call it, it will fail because it NSNumberdoes not respond to -mutableCopyWithZone:.

You can see it with

assert([NSObject instanceMethodForSelector:@selector(mutableCopy)] == [NSNumber instanceMethodForSelector:@selector(mutableCopy)])

bbum - , , .

+5

. , -mutableCopy. ( , @(REALLYBIGNUMBERTHATISNEARMAX) ).

, respondsToSelector: . isKindOfClass:. , (NSArray vs. NSMutableArray, , - - , ).

, . , @protocol, @optional.

+4

Source: https://habr.com/ru/post/1668957/


All Articles