解析数组的每个元素 - iOS

时间:2014-08-08 07:24:26

标签: ios objective-c ios7 nsmutablearray nspredicate

我有一个如下例子的数组:

[
    {
        "lx": 144,
        "ly": 57,
        "mx": 144,
        "my": 56
    },
    {
        "lx": 321,
        "ly": -4,
        "mx": 298,
        "my": 16
    }
]

我想设置每个元素的半值。

简而言之,我想要跟随之类的东西。

[
    {
        "lx": 72,
        "ly": 28.5,
        "mx": 72,
        "my": 28
    },
    {
        "lx": 160.5,
        "ly": -2,
        "mx": 149,
        "my": 8
    }
]

我正在使用以下代码:

    NSMutableArray * tempArray = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i < jsonArray.count; i++)
    {
        NSMutableDictionary * tempDict = [NSMutableDictionary dictionaryWithDictionary:(NSDictionary *)jsonArray[i]];
        tempDict[@"lx"] = @([tempDict[@"lx"] intValue]/2);
        tempDict[@"ly"] = @([tempDict[@"ly"] intValue]/2);
        tempDict[@"mx"] = @([tempDict[@"mx"] intValue]/2);
        tempDict[@"my"] = @([tempDict[@"my"] intValue]/2);
        [tempArray addObject:tempDict];
    }

我已经完成了一个循环,它可以正常处理少量数据。

但是当我有大量数据时,App行为会变慢。

任何帮助将不胜感激

...谢谢

3 个答案:

答案 0 :(得分:1)

也许您可以在后台线程中异步计算它,这样就不会阻止UI。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    // Code to execute in background thread
});

答案 1 :(得分:1)

在您的代码中,我发现您不会考虑浮动结果,因此我可以使用移位运算符而不是分割。

// allocate enough memory
NSMutableArray * tempArray = [NSMutableArray arrayWithCapacity:[jsonArray count]];
// fast enumerate
for (NSDictionary *dict in jsonArray) {
    NSMutableDictionary * tempDict = [NSMutableDictionary dictionaryWithDictionary:dict];
    // use shift operator instead of dividing by 2
    tempDict[@"lx"] = @([tempDict[@"lx"] intValue]>>1);
    tempDict[@"ly"] = @([tempDict[@"ly"] intValue]>>1);
    tempDict[@"mx"] = @([tempDict[@"mx"] intValue]>>1);
    tempDict[@"my"] = @([tempDict[@"my"] intValue]>>1);
    [tempArray addObject:tempDict];
}

我不认为这种方法会提高性能,因为我们必须枚举所有项目,时间复杂度不会改变。

答案 2 :(得分:-1)

将你的评论发给另一个答案:我想减慢解析数据的过程

如果您想将控制权返回给主线程以允许其他操作发生,您可以使用

[[NSRunLoop mainRunLoop] runUntilDate:[NSDate date]];

将暂时暂停当前的数据处理循环并允许其他事情发生。显然,如果你想减慢更多的速度,你也可以将[NSDate date]更改为将来更进一步的日期。