Objective-Cの中平等をチェック
-
21-09-2019 - |
質問
どのように私は、辞書内のキーは、メソッドのパラメータの文字列と同じであるチェックしますか? すなわちは、コードの下に、dictobjはNSMutableDictionaryのオブジェクトであり、dictobjで各キーのために私は、文字列を比較する必要があります。これを達成するには?私はNSStringの??
の鍵をtypecase必要があります-(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");
あなたは文字列を比較すると、は、あなたは通常、あなたが-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を比較するために、はisEqual:
のより一般的なNSObject
メソッドを使用する必要がありますオブジェクト。 -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
}
}
}
所属していません StackOverflow