从NSDictionary到NSString的所有键和对象

Rob*_*bie 1 objective-c nsdictionary nsstring

我有一个NSDictionary,我想将它的所有对象和键放入NSString中,这样我最终可以在这样的标签中显示它们:

key1:object1

key2:object2

key3:object3

......

有任何想法吗?

Pau*_*l.s 6

构建字符串,然后将其设置为标签文本.

NSMutableString *myString = [[NSMutableString alloc] init];

[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    [myString appendFormat:@"%@ : %@\n", key, obj];
}];

self.label.text = myString;
Run Code Online (Sandbox Code Playgroud)

注意

格式说明符状态的docs(String Programming Guide)%@:

%@
Objective-C对象,打印为descriptionWithLocale返回的字符串:如果可用,或其他说明.也适用于CFTypeRef对象,返回CFCopyDescription函数的结果.

因此,如果这些是您自己在字典中的自定义对象,则您很可能需要覆盖该description方法以提供更有意义的输出

更新

你提到你需要你的输出按键排序 - 字典没有排序所以你必须以不同的方式做 - 这个例子假设你的键是字符串

NSArray *sortedKeys = [[dictionary allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

NSMutableString *myString = [[NSMutableString alloc] init];

for (NSString *key in sortedKeys) {
    [myString appendFormat:@"%@ : %@\n", key, [dictionary objectForKey:key]];
}

self.label.text = myString;
Run Code Online (Sandbox Code Playgroud)