如何重组对象数组

时间:2015-03-16 21:05:23

标签: ios objective-c arrays parse-platform nsdictionary

我正在查询一个类型为NSArray的对象,该对象在我的后端parse.com上调用了消息,如下所示:

 self.messages = (
"<lean: 0x7fcf98665140, objectId: vglE1UJ5KI, localId: (null)> {\n    messageBody = Jj;\n    recipientId = XvvxETqjph;\n    senderId = XvvxETqjph;\n    timestamp = \"1424991590106.210938\";\n}",
"<lean: 0x7fcf98667940, objectId: rgBFYBMKlU, localId: (null)> {\n    messageBody = \"test 3 from ian\";\n    recipientId = XvvxETqjph;\n    senderId = Hoy7UjLzOh;\n    timestamp = \"1424631667110.638184\";\n}",
"<lean: 0x7fcf98667f30, objectId: hB5uhwsYsu, localId: (null)> {\n    messageBody = \"test 2 from user1\";\n    recipientId = XvvxETqjph;\n    senderId = VQzxWbDnal;\n    timestamp = \"1424630904935.162109\";\n}",
"<lean: 0x7fcf986685b0, objectId: dOe2B9oq5b, localId: (null)> {\n    messageBody = \"test 1\";\n    recipientId = XvvxETqjph;\n    senderId = XvvxETqjph;\n    timestamp = \"1424630808309.478027\";\n}"
)

所以它基本上是一个字典对象数组。我如何将其重新格式化为正常的字典数组,如下所示:

self.messages = (
"{\n objectId: vglE1UJ5KI;\n    messageBody = Jj;\n    recipientId = XvvxETqjph;\n    senderId = XvvxETqjph;\n    timestamp = \"1424991590106.210938\";\n}",
"{\n objectId: rgBFYBMKlU;\n    messageBody = \"test 3 from ian\";\n    recipientId = XvvxETqjph;\n    senderId = Hoy7UjLzOh;\n    timestamp = \"1424631667110.638184\";\n}",
"{\n objectId: hB5uhwsYsu;\n    messageBody = \"test 2 from user1\";\n    recipientId = XvvxETqjph;\n    senderId = VQzxWbDnal;\n    timestamp = \"1424630904935.162109\";\n}",
"{\n objectId: dOe2B9oq5b;\n    messageBody = \"test 1\";\n    recipientId = XvvxETqjph;\n    senderId = XvvxETqjph;\n    timestamp = \"1424630808309.478027\";\n}"
)

1 个答案:

答案 0 :(得分:1)

从解析返回的PFObject非常像字典,只要它响应allKeysobjectForKey:以及setObject:forKey:,依此类推。我已经看到几个提问者因PFObject实现description的方式而感到困惑,因此它如何在控制台上打印,使它看起来不像字典而不是它应该存在。

无论如何,如果出于某种原因,一个人真的必须拥有NSDrray的NSArray,而不是类似字典的NSArray对象,那么他们可以使用这样的代码:

- (NSDictionary *)dictionaryFromPFObject:(PFObject *)pfObject {
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
    for (NSString *key in [pfObject allKeys]) {
        dictionary[key] = [pfObject objectForKey:key];
    }
    return dictionary;
}

...并从这样的查找完成块中调用它:

[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (!error) {
        NSMutableArray *array = [NSMutableArray array];
        for (PFObject *pfObject in objects) {
            [array addObject:[self dictionaryFromPFObject:pfObject]];
        }
    }
}];