iOS - 使用谓词过滤集的性能

时间:2013-04-22 17:20:56

标签: ios performance nspredicate nsset

我在一些较旧的设备上遇到UI口吃/暂停(例如ipod touch 4th gen),我将其缩小到这段代码:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"gender != %@ && catId != %@", [NSNumber numberWithInt:0], [NSNumber numberWithInt:7]];
NSSet *filteredCats = [cats filteredSetUsingPredicate:predicate]; //cats is an NSSet

如果我注释掉这两行代码并改为执行此操作:

NSSet *filteredCats = cats;

表现非常流畅。那么如何在不引起屏幕更新的短暂停顿的情况下改进此过滤呢?

1 个答案:

答案 0 :(得分:2)

您可以异步进行过滤,这有助于提高性能:

 __weak ViewController *bSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul),^{

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"gender != %@ && catId != %@", [NSNumber numberWithInt:0], [NSNumber numberWithInt:7]];

    NSSet *filteredCats = [cats filteredSetUsingPredicate:predicate]; 

    dispatch_async(dispatch_get_main_queue(), ^{ 
        [bSelf updateMyViewWithFilteredSet:filteredCats]; 
    }
}