2010-02-19 118 views
13

如何檢查字典中的密鑰與方法參數中的字符串相同? 即在下面的代碼中,dictobj是NSMutableDictionary的對象,並且對於dictobj中的每個鍵我需要與字符串進行比較。如何實現這一目標?我應該鍵入NSString的鍵?在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

當您使用==運算符時,您正在比較指針值。只有當你比較的對象是同一個內存地址的完全相同的對象時,這纔會起作用。例如,該代碼將返回These objects are different因爲雖然字符串是相同的,它們存儲在不同的位置存儲:

NSString* foo = @"Foo"; 
NSString* bar = [NSString stringWithFormat:@"%@",foo]; 
if(foo == bar) 
    NSLog(@"These objects are the same"); 
else 
    NSLog(@"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"); 

比較隨意Objective-C對象,你應該使用的NSObject更一般isEqual:方法。 -isEqualToString:-isEqual:的優化版本,您應該在知道這兩個對象都是NSString對象時使用該版本。

- (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 2010-02-19 03:52:06