【问题标题】:Loop through NSMutableArray of custom objects in the most memory efficient way以最节省内存的方式循环自定义对象的 NSMutableArray
【发布时间】:2010-12-12 19:30:39
【问题描述】:

循环遍历自定义对象的 NSMutableArray 的最节省内存的方法是什么? 我需要检查数组中每个对象的值,并返回数组中有多少该类型的对象。

【问题讨论】:

    标签: iphone objective-c memory-management


    【解决方案1】:
    for (WhateverYourClassNameIs *whateverNameYouWant in yourArrayName) {
        [whateverNameYouWant performSelector];
        more code here;
    }
    

    它被称为快速枚举,是 Objective C 2.0 中的一项新功能,可在 iPhone 上使用。

    【讨论】:

    • 这是一种更好的内存管理方式,但我确实喜欢 Dave DeLong 关于谓词的帖子。
    【解决方案2】:

    我可能只使用谓词,就像这样:

    NSArray * filtered = [myArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"aProperty = %@", @"someValue"]];
    NSLog(@"number of items where aProperty = someValue: %d", [filtered count]);
    

    编辑:此代码在功能上等同于:

    NSMutableArray * filtered = [NSMutableArray array];
    for (MyCustomObject * object in myArray) {
      if ([[object aProperty] isEqual:@"someValue"]) {
        [filtered addObject:object];
      }
    }
    

    【讨论】:

    • 想对这段代码做一点解释吗?我是 iPhone 新手和 Obj-C 新手。你的代码看起来很小而且很棒,但我讨厌使用我不理解的东西。
    • 阅读 filteredArrayUsingPredicateNSPredicate predicateWithFormat 的文档
    • 感谢您的解释,这太棒了。在从编写游戏转向基于 Core Data 的工作之后,我才开始使用谓词,但我知道它们是如此强大。
    • @refulgentis - 一旦你掌握了谓词的窍门(这真是太棒了,顺便说一句),就可以尽情享受关键路径的乐趣。我最近才开始接触这些,它们非常有趣。 =D
    • 代码干净整洁!但是,内存效率不高,因为它会创建一个包含所有过滤元素的新数组。
    猜你喜欢
    • 2013-10-30
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多