objective-c 以最节省内存的方式循环自定义对象的 NSMutableArray

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1670163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 22:27:21  来源:igfitidea点击:

Loop through NSMutableArray of custom objects in the most memory efficient way

iphoneobjective-cmemory-management

提问by James P. Wright

What is the most memory efficient way to loop through an NSMutableArray of custom objects? I need to check a value in each object in the array and return how many of that type of object is in the array.

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

回答by refulgentis

for (WhateverYourClassNameIs *whateverNameYouWant in yourArrayName) {
    [whateverNameYouWant performSelector];
    more code here;
}

It's called fast enumeration and was a new feature with Objective C 2.0, which is available on the iPhone.

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

回答by Dave DeLong

I'd probably just use a predicate, which would be something like this:

我可能只是使用一个谓词,这将是这样的:

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

Edit: This code is functionally equivalent to:

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

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