簡體   English   中英

在Objective-C中檢查是否相等

[英]Checking for equality in Objective-C

如何檢查字典中的鍵與方法參數中的字符串相同? 即在下面的代碼中,dictobj是NSMutableDictionary的對象,對於dictobj中的每個鍵,我需要與字符串進行比較。 如何實現呢? 我應該輸入NSString的大小寫鍵嗎?

-(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
          }
     }
}

當使用==運算符時,您正在比較指針值。 僅當您要比較的對象是完全相同的對象,並且在相同的內存地址時才有效。 例如,此代碼將返回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");

比較字符串時,通常需要比較字符串的文本內容而不是指針,因此您應該使用NSString-isEqualToString:方法。 這段代碼將返回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
          }
     }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM