0

私は自分の生活を少し楽にしようとしています。NSDictionaryから次のような多くの値を取得します。

//First, make sure the object exist 
if ([myDict objectForKey: @"value"])
{
     NSString *string = [myDict objectForKey: @"value"]; 
     //Maybe do other things with the string here... 
}

アプリを制御するためにたくさんのものを保存するファイル(Variables.h)があります。そこにいくつかのヘルパーメソッドを入れておくといいでしょう。したがって、上記のコードを実行する代わりに、Variables.hにc ++関数を入れたいので、これを実行できます。

NSString *string = GetDictValue(myDictionary, @"value"); 

そのc++メソッドをどのように記述しますか?

前もって感謝します

4

2 に答える 2

2

これは技術的にはac関数だと思いますが、C++は厳密な要件です

static NSString* GetDictValue(NSDictionary* dict, NSString* key)
{
    if ([dict objectForKey:key])
    {
         NSString *string = [dict objectForKey:key]; 
         return string;
    }
    else 
    {
        return nil;
    }
}

id必要に応じて使用とキャストを検討してください。

static id GetDictValue(NSDictionary* dict, NSString* key)
{
    if ([dict objectForKey:key])
    {
         id value = [dict objectForKey:key]; 
         return value;
    }
    else 
    {
        return nil;
    }
}
于 2012-06-07T10:50:44.590 に答える
1

個人的には、ルックアップを取り除くために、テストを次のように書き直します。

NSString *string = [myDict objectForKey: @"value"]; 
if (string)
{
     // Do stuff.
}

ただし、欠落しているキーのデフォルト値が必要で、C ++関数である必要がない場合は、カテゴリを使用してNSDictionaryを拡張するのがより慣用的な解決策になると思います

完全にテストされておらず、コンパイルされていないコード:

@interface NSDictionary (MyNSDictionaryExtensions)
- (NSString*) objectForKey: (NSString*) key withDefaultValue: (NSString*) theDefault;
- (NSString*) safeObjectForKey: (NSString*) key;
@end

@implementation NSDictionary (MyNSDictionaryExtensions)
- (NSString*) objectForKey: (NSString*) key withDefaultValue: (NSString*) theDefault
{
    NSString* value = (NSString*) [self objectForKey: key];
    return value ? value : theDefault;
}
- (NSString*) safeObjectForKey: (NSString*) key
{
    return [self objectForKey: key withDefaultValue: @"Nope, not here"];
}
@end
于 2012-06-07T14:43:55.290 に答える