从多个NSArrays中检索1个特定密钥并将它们一起添加

时间:2015-01-09 23:08:20

标签: ios foreach parse-platform nsarray nsinteger

在我的应用中,我需要遍历每个NSArray,获取与关键字'人员关联的NSInteger。在NSArray中,然后将它们全部添加到一起。首先从每个NSInteger检索每个特定NSArray的起点是什么?

有问题的数组在控制台中返回如下内容。

(
    "<Prayers:DDomBXIONY:(null)> {\n    Anonymous = 1;\n    DeviceID = 123;\n    FirstName = Name;\n    LastName = Name;\n    Location = HI;\n    PrayerWarriors = 8;\n    Request = Hi;\n    Title = Hi;\n    UserId = RtXN6QZsgaIiPw4SjFWGtkxXx;\n    dateMade = \"Jan_09_2015\";\n}"
)

基本上只需从每个PrayerWarriors键中检索NSInteger,并将它们全部加在一起。

(
    "<Prayers:DDomBXIONY:(null)> {\n    Anonymous = 1;\n    DeviceID = 123;\n    FirstName = Name;\n    LastName = Name;\n    Location = HI;\n    PrayerWarriors = 8;\n    Request = Hi;\n    Title = Hi;\n    UserId = RtXN6QZsgaIiPw4SjFWGtkxXx;\n    dateMade = \"Jan_09_2015\";\n}",
    "<Prayers:yG7GC4bCIH:(null)> {\n    Anonymous = 1;\n    DeviceID = 123;\n    FirstName = Name;\n    LastName = Name;\n    Location = bye;\n    PrayerWarriors = 0;\n    Request = bye;\n    Title = bye;\n    UserId = RtXN6QZsgaIiPw4SjFWGtkxXx;\n    dateMade = \"Jan_09_2015\";\n}"
)

2 个答案:

答案 0 :(得分:0)

因此,如果不准确了解PFObject的工作原理,我会假设它就像一本字典。

将每个对象添加到单个数组中:

NSMutableArray *arrayHoldingPrayersObjects = [NSMutableArray alloc] init];
arrayHoldingPrayersObjects[0] = prayerObject1;
arrayHoldingPrayersObjects[1] = prayerObject2;
arrayHoldingPrayersObjects[2] = prayerObject3;

等...

然后在for循环之外创建一个整数变量并遍历对象,在每次迭代时为PrayerWarrior添加值。

int totalPrayerWarriors = 0;
for (int i = 0; i < arrayHoldingPrayersObjects.count; i++)
{
    NSMutableDictionary *prayerObject = arrayHoldingPrayersObjects[i];
    totalPrayerWarriors += [prayerObject objectForKey:@"PrayerWarriors"] intValue];
}

您应该从所有阵列获得正确的总数。做一些测试,以确保它对您来说准确。希望这会有所帮助。

*编辑

你得到的错误表明它实际上是一个NSMutableArray,你无法使用像objectForKey这样的方法访问它,所以......必须有一个PFObject提供的方法允许你这样做。或者,如果PrayerWarriors可靠地是数组中的第[5]个值(包括0),那么您可以通过索引访问它。

替换行:

NSMutableDictionary *prayerObject = arrayHoldingPrayersObjects[i];
totalPrayerWarriors += [prayerObject objectForKey:@"PrayerWarriors"] intValue];

NSMutableArray *prayerObject = arrayHoldingPrayersObjects[i];
totalPrayerWarriors += prayerObject[5];

答案 1 :(得分:0)

不确定可变数组的来源。据我所知,Parse.com将始终生成不可变数组。所以,假设您已经通过以下方式检索了Prayers:

PFQuery *query = [PFQuery queryWithClassName:@"Prayers"];
[query findObjectsInBackgroundWithBlock:^(NSArray *prayers, NSError *error) {
    // see how it's an NSArray, not mutable
}];

现在您想要检索PrayerWarrior属性的总数,所以......

[query findObjectsInBackgroundWithBlock:^(NSArray *prayers, NSError *error) {
    NSInteger total = 0;
    for (PFObject *p in prayers) {
        NSNumber *warriorCount = p[@"PrayerWarriors"];
        total += [warriorCount intValue];  // notice we cannot add nsnumbers directly (we need intValue)
    }
    NSLog(@"total warriors = %d", total);
}];