In ObjC, how does one determine whether the object can be changed or not?
How to judge whether the object is changeable or not in ObjC?
How can we determine NSString and NSMutableString?
Question
BOOL result = [@"123" isKindOfClass:[NSMutableString class]]; // A:YES B:NO
This is simple, of course, B. The String constant is NSString. So the correct answer is A, is there A way to catch up with questions. We recommend that you have an interview with this question.
First, we should use Baidu objc's cluster-like concept and then the factory model. This note only describes how to judge, and opens a portal to fight for monsters.
View the results obtained from the console
id str0 = [NSString alloc];//NSPlaceholderString->NSString id str1 = [[NSString alloc] init];//__NSCFConstantString->__NSCFString->NSMutableString->NSString id str3 = [NSString stringWithFormat:@"123"];//NSTaggedPointerString->NSString id str4 = [NSMutableString alloc];//NSPlaceholderMutableString->NSMutableString->NSString id str5 = [NSMutableString new];//__NSCFString->NSMutableString->NSString
The String constant, that is, the type obtained by the str1 creation method is _ NSCFConstantString, and the class of NSMutableString is explicit. In any case, be brave enough to question Apple's designs. In addition, the Array and Dictionary at the end do not have such brains. We don't know how many sub-classes are in the black box. According to the inverted big method:
So now you can determine whether a string is variable.
BOOL isMutable = [str isMemberOfClass: NSClassFromString (@ "_ NSCFString")]; // please note that isMemberOfClass: This method should not be used as isKindOfClass:
Let's take a look at the console results of Array.
NSArray* arr0 = [[NSArray alloc] init];//__NSArray0->NSArray NSArray* arr1 = [NSArray arrayWithObject:@"123"];//__NSArrayI->NSArray NSMutableArray* arr3 = [[NSMutableArray alloc] init];//__NSArrayM->NSMutableArray->NSArray
We can find that although NSArray has a large number of sub-accounts, there will be no close kinship like String.
It can be used to determine whether the Array is immutable. You do not need to write the string type.
BOOL notMutable = [arr isKindOfClass:[NSArray class]]&&![arr isKindOfClass:[NSMutableArray class]];
Dictionary is the same as NSArray.
Resend: original