2012-10-29 52 views
2
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是禁止的?const关键字在objective-c

看到这样的打击:

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“常量”关键字就像++?

============================================ @看到https://softwareengineering.stackexchange.com/questions/151463/do-people-use-const-a-lot-when-programming-in-objective-c

回答

3

'常量' 确实对Objective-C的对象罢了。你不能做你想要的东西。

4

麻烦的是,虽然你宣称str1是的NSMutableString一个实例,它实际上是一个不同的子类的NSString --in特定的实例,它是__NSCFConstantString默认实例,虽然this class can be changed by setting a compiler flag。这是从@""返回的那种字符串。

为了解决这个问题,只需使用

const NSMutableString *str1 = [NSMutableString stringWithFormat:@"1"];