4

現在、次の方法を使用して、データがNullでないことを検証しています。

if ([[response objectForKey:@"field"] class] != [NSNull class])
    NSString *temp = [response objectForKey:@"field"];
else
    NSString *temp = @"";

問題は、応答ディクショナリに数百の属性(およびそれぞれの値)が含まれている場合に発生します。この種の条件を辞書のすべての要素に追加する必要があります。

達成するための他の方法はありますか?

Webサービスに変更を加えるための提案はありますか(データベースにnull値を挿入しないことを除く)?

どんなアイデアでも、誰でも??

4

4 に答える 4

7

私がやったことは、NSDictionaryにカテゴリを置くことです

@interface NSDictionary (CategoryName)

/**
 * Returns the object for the given key, if it is in the dictionary, else nil.
 * This is useful when using SBJSON, as that will return [NSNull null] if the value was 'null' in the parsed JSON.
 * @param The key to use
 * @return The object or, if the object was not set in the dictionary or was NSNull, nil
 */
- (id)objectOrNilForKey:(id)aKey;



@end


@implementation NSDictionary (CategoryName)

- (id)objectOrNilForKey:(id)aKey {
    id object = [self objectForKey:aKey];
    return [object isEqual:[NSNull null]] ? nil : object;
}

@end

その後、あなたはただ使うことができます

[response objectOrNilForKey:@"field"];

必要に応じて、これを変更して空白の文字列を返すことができます。

于 2012-04-17T05:48:51.263 に答える
0

最初のマイナーなポイント:あなたのテストは慣用的ではありません、あなたは使うべきです

if (![[response objectForKey:@"field"] isEqual: [NSNull null]])

の値を持つ辞書内のすべてのキーを[NSNull null]空の文字列にリセットする場合、それを修正する最も簡単な方法は次のとおりです。

for (id key in [response allKeysForObject: [NSNull null]])
{
    [response setObject: @"" forKey: key];
}

上記responseは、変更可能な辞書であると想定しています。

しかし、私はあなたが本当にあなたのデザインを見直す必要があると思います。[NSNull null]データベースで値が許可されていない場合は、値を許可しないでください。

于 2012-04-10T09:34:26.790 に答える
0

何が必要かは私にはわかりませんが、次のようになります。

キーの値がNULLでないかどうかを確認する必要がある場合は、次のように実行できます。

for(NSString* key in dict) {
   if( ![dict valueForKey: key] ) {
       [dict setValue: @"" forKey: key];
   }
}

必要なキーのセットがある場合は、静的配列を作成してからこれを行うことができます。

static NSArray* req_keys = [[NSArray alloc] initWithObjects: @"k1", @"k2", @"k3", @"k4", nil];

次に、データをチェックする方法で:

NSMutableSet* s = [NSMutableSet setWithArray: req_keys];

NSSet* s2 = [NSSet setWithArray: [d allKeys]];

[s minusSet: s2];
if( s.count ) {
    NSString* err_str = @"Error. These fields are empty: ";
    for(NSString* field in s) {
        err_str = [err_str stringByAppendingFormat: @"%@ ", field];
    }
    NSLog(@"%@", err_str);
}
于 2012-04-10T09:35:42.950 に答える
0
static inline NSDictionary* DictionaryRemovingNulls(NSDictionary *aDictionary) {

  NSMutableDictionary *returnValue = [[NSMutableDictionary alloc] initWithDictionary:aDictionary];
  for (id key in [aDictionary allKeysForObject: [NSNull null]]) {
    [returnValue setObject: @"" forKey: key];
  }
  return returnValue;
}


response = DictionaryRemovingNulls(response);
于 2014-12-30T12:57:03.797 に答える