关于NSDictionaries的一个重要问题

时间:2010-06-24 13:51:01

标签: cocoa cocoa-touch nsarray nsdictionary nsmutablestring

我有一个带NSStrings的NSDictionary

某些valueForKey:@“Key”没有条目,所以它是(null)

NSMutableString* addressDictionaryToString = [NSMutableString string];  // use mutable string!
for (NSDictionary* item in address) {     // use fast enumeration!
        [addressDictionaryToString appendFormat:@"%@, %@, %@, %@",
         [item objectForKey:@"Street"],         
         [item objectForKey:@"City"],
         [item objectForKey:@"State"],
         [item objectForKey:@"ZIP"]
         ];
    NSLog(@"MutableString: %@", addressDictionaryToString);
}

所以我想构建一个NSMutableString,但过滤掉那些为null的键。有什么想法吗?

UPDATE :::::

基本上我希望我的结果字符串看起来像

1 Infinite Loop,Cupertino,CA,95014(如果所有字段都可用)

如果我错过了街道那么

Cupertino,CA,95014

如果我错过了国家那么

1 Infinite Loop,Cupertino,95014

如果我只有状态那么它应该打印

CA

(注意最后一个元素没有逗号)

2 个答案:

答案 0 :(得分:1)

检查密钥的值是否如何?

NSMutableString * addressDictionaryToString = [NSMutableString string];
for (NSDictionary * item in address)
{
    if ([item objectForKey:@"Street"])
        [addressDictionaryToString appendFormat:@"%@, ", 
         [item objectForKey:@"Street"]];
    if ([item objectForKey:@"City"])
        [addressDictionaryToString appendFormat:@"%@, ", 
         [item objectForKey:@"City"]];
    if ([item objectForKey:@"State"])
        [addressDictionaryToString appendFormat:@"%@, ", 
         [item objectForKey:@"State"]];
    if ([item objectForKey:@"ZIP"])
        [addressDictionaryToString appendFormat:@"%@, ", 
         [item objectForKey:@"ZIP"]];
    NSLog(@"MutableString: %@", addressDictionaryToString);
}

问题是,在您的上一个问题中,您说过您的目标是创建一个CSV文件。如果您的行具有不同数量的字段且没有可靠的方法来识别每个字段,那么它在技术上并不是有效的。

相反,你可以试试这个:

NSMutableString * addressDictionaryToString = [NSMutableString string];
for (NSDictionary * item in address)
{
    [addressDictionaryToString appendFormat:@"%@,", 
     ([item objectForKey:@"Street"]) ? [item objectForKey:@"Street"] : @"" ];
    // ...
    NSLog(@"MutableString: %@", addressDictionaryToString);
}

检查是否存在值,如果有值,则插入该值,或者只插入一个空字符串(导致“value,value,value ...”)。还记得逗号之后不应该有空格,所以我从这个例子中删除了它。

答案 1 :(得分:0)

不完全确定你要做什么但是这个:

NSDictionary *d=[NSDictionary dictionaryWithObject:[NSNull null] forKey:@"ns"];
NSString *n=[@"Steve " stringByAppendingFormat:@"%@",[d objectForKey:@"ns"]];
NSLog(@"%@",n);

...打印:

Steve <null>

如果密钥本身不存在,那么当您尝试获取不存在密钥的值时,它将抛出异常。在这种情况下,唯一的办法是在尝试使用它来检索值之前检查每个字典中的密钥。

相关问题