Hello,
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?
views:
1558answers:
4makeObjectsPerformSelector: 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:)];
I hope I'm interpreting this correctly...
If you do [myArray makeObjectsPerformSelector:someSelector], you're effectively just iterating through myArray and sending the selector message to each object. The array is unchanged because makeObjectsPerformSelector isn't allowed to change its contents.
So in the end, you've got the same array with the same objects.
If I use it on an array, will it change the existing array or return a new one?
No.
First off, read the signature:
- (void)makeObjectsPerformSelector:(SEL)aSelector
void
, with no stars after it, means “does not return anything”.
Second, note that this is a method of NSArray, which is an immutable class. Therefore, makeObjectsPerformSelector:
does not mutate the receiving array, because that's impossible.
There is NSMutableArray, and since that's a subclass of NSArray, it inherits makeObjectsPerformSelector:
. However, if NSMutableArray changed that method's behavior, its documentation would have its own listing for the method (see the many definitions of init
in various classes' documentation). There's no such listing, so you can safely (and correctly) infer that -[NSMutableArray makeObjectsPerformSelector:]
works exactly the same way as -[NSArray makeObjectsPerformSelector:]
.
The objects can modify themselves in response to your message, but the array itself will contain the same objects after makeObjectsPerformSelector:
as before it.
Further to other answers, if you do want create a new array with the result of calling a method, you can do this:
NSArray *derivedArray = [originalArray valueForKey:@"foo"];
This will only work if your objects can handle a '-valueForKey:@"foo"' message and obviously, is only suitable for methods which take no arguments and return a non-nil value.