int main(int argc, char *argv[]) {
@autoreleasepool {
const int x = 1;
const NSMutableArray *array1 = [NSMutableArray array];
const NSMutableString *str1 = @"1";
NSString * const str2 = @"2";
// x = 2; compile error
[array1 addObject:@"2"]; // ok
// [str1 appendString:@"2"]; // runtime error
// Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to mutate immutable object with appendString:'
// str2 = @"3"; compile error
}
}
我的问题是为什么 array1 addObject 是合法的,为什么 str1 appendString 是被禁止的?
看到这个打击:
NSMutableString *f2(const NSMutableString * const x) {
[x appendString: @" world!"];
return x;
}
int main(int argc, char *argv[]) {
@autoreleasepool {
NSMutableString *x = [@"Hello" mutableCopy];
NSLog(@"%@", f2(x));
}
return 0;
}
以及为什么这段代码是合法的,我怎样才能像在 c++ 中一样使用 'const' 关键字使对象不可变?
==============================================@see https:// softwareengineering.stackexchange.com/questions/151463/do-people-use-const-a-lot-when-programming-in-objective-c