2012-10-29 47 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"];