2012-10-29 7 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이 금지되는 이유입니까? Objective-c의 const 키워드

이 타격을 참조하십시오

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를'키워드를 사용하여 객체는 불변 할 수 ++?

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

답변

3

'const를'목표 - C 객체에 아무 작업도 수행하지 않습니다를 사용하여이 문제를 해결합니다. 당신은 당신이 요구하는 것을 할 수 없습니다.

4

의 문제점은 당신이 NSMutableString의 인스턴스로 str1을 선언하지만, 그것은 특정 이대로 더 NSString의 다른 서브 클래스의 인스턴스가 사실이라는 것이다 참조는 this class can be changed by setting a compiler flag하지만, 기본적으로 __NSCFConstantString의 인스턴스입니다. 이것은 @""에서 반환되는 문자열의 일종입니다.

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