问题描述
我想在一个阵列中的所有对象进行选择。我发现适当命名的 makeObjectsPerformSelector:
方法,但我与它的问题。如果我用它的阵列上,它将改变现有的阵列或返回一个新的?如果修改现有的对象,什么是返回一个新的数组,选择最简单的方法应用?
I want to make all objects in an array perform a selector. I've discovered the appropriately named makeObjectsPerformSelector:
method, but I have a question with it. If I use it on an array, will it change the existing array or return a new one? If it modifies the existing object, what be the easiest way to return a new array with the selector applied?
推荐答案
makeObjectsPerformSelector:将运行对阵列中的每个对象选择。如果这些对象由选择修改它们将被修改。它不返回任何东西。现在,有一个陷阱,它在默认情况下在可可大多数副本复印件浅,这意味着你得到一个新的数组,但底层对象指向是相同的对象。您将需要使用initWithArray:copyItems使它复制根级别的项目也是如此。如果你想包含改变对象的新阵列,以及旧的阵列做这样的事:
makeObjectsPerformSelector: is going to run that selector against every object in the array. If those objects are modified by the selector they will be modified. It does not return anything. Now, there is a catch, which that by default most copies in Cocoa are shallow copies, which means you get a new array, but the underlying objects it points to are the same objects. You will need to use initWithArray:copyItems to make it copy the root level items as well. If you want a new array containing the altered objects as well as the old array do something like this:
NSArray *newArray = [[NSArray alloc] initWithArray:oldArray copyItems:YES];
[newArray makeObjectsPerformSelector:@selector(doSomethingToObject)];
这篇关于makeObjectsPerformSelector:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!