2010-02-19 5 views
13

사전의 키를 확인하는 방법은 메서드 매개 변수의 문자열과 동일합니까? 즉, 아래의 코드에서 dictobj는 NSMutableDictionary의 객체이고 dictobj의 각 키에 대해 문자열과 비교해야합니다. 이것을 달성하는 방법? NSString에 키를 typecase해야합니까 ??Objective-C에서 동등성 검사

-(void)CheckKeyWithString:(NSString *)string 
{ 
    //foreach key in NSMutableDictionary 
    for(id key in dictobj) 
    { 
     //Check if key is equal to string 
     if(key == string)// this is wrong since key is of type id and string is of NSString,Control doesn't come into this line 
      { 
      //do some operation 
      } 
    } 
} 

답변

38

== 연산자를 사용할 때 포인터 값을 비교합니다. 이는 비교중인 객체가 동일한 메모리 주소에있는 정확히 동일한 객체 일 때만 작동합니다. 당신이 문자열을 비교할 때

NSString* foo = @"Foo"; 
NSString* bar = [NSString stringWithFormat:@"%@",foo]; 
if(foo == bar) 
    NSLog(@"These objects are the same"); 
else 
    NSLog(@"These objects are different"); 

, 당신은 일반적으로 문자열의 텍스트 내용을 비교보다는하려면 : 문자열이 동일하지만, 그들은 메모리에 다른 위치에 저장되어 있기 때문에 예를 들어,이 코드는 These objects are different를 반환합니다 그들의 포인터, 그래서 -isEqualToString:NSString의해야합니다. 이 문자열 객체의 값을 비교하기 때문에이 코드는 오히려 자신의 포인터 값보다 These strings are the same를 반환합니다

NSString* foo = @"Foo"; 
NSString* bar = [NSString stringWithFormat:@"%@",foo]; 
if([foo isEqualToString:bar]) 
    NSLog(@"These strings are the same"); 
else 
    NSLog(@"These string are different"); 

는 비교하기 위해 임의의 오브젝티브 C는 NSObject의 일반적인 isEqual: 방법을 사용한다 객체. -isEqualToString:은 두 개체가 NSString 개체라는 것을 알고있을 때 사용해야하는 -isEqual:의 최적화 된 버전입니다.

- (void)CheckKeyWithString:(NSString *)string 
{ 
    //foreach key in NSMutableDictionary 
    for(id key in dictobj) 
    { 
     //Check if key is equal to string 
     if([key isEqual:string]) 
      { 
      //do some operation 
      } 
    } 
} 
+0

우수한 ... 고맙다 롭. – suse