Friday, May 31, 2013

NSArray makeObjectsPerformSelector example in Objective C (iOS).


NSArray makeObjectsPerformSelector

Sends to each object in the array the message identified by a given selector, starting with the first object and continuing through the array to the last object.

- (void)makeObjectsPerformSelector:(SEL)aSelector

Parameters
aSelector
A selector that identifies the message to send to the objects in the array. The method must not take any arguments, and must not have the side effect of modifying the receiving array.

Discussion of [NSArray makeObjectsPerformSelector]
This method raises an NSInvalidArgumentException if aSelector is NULL.

NSArray makeObjectsPerformSelector example.
NSArray *newArray = [[NSArray alloc] initWithArray:oldArray copyItems:YES];
[newArray makeObjectsPerformSelector:@selector(doSomethingToObject:)];

Example of [NSArray makeObjectsPerformSelector].
@interface UIButton(setEnabledWithObject)
- (void)setEnabledWithNSNumber:(NSNumber *)bNum;
@end

@implementation UIButton(setEnabledWithObject)
- (void)setEnabledWithNSNumber:(NSNumber *)bNum {
    [self setEnabled:[bNum boolValue]];
}
@end
and then you could use

[buttons makeObjectsPerformSelector:@selector(setEnabledWithNSNumber:) withObject:[NSNumber numberWithBool:NO]];
[buttons makeObjectsPerformSelector:@selector(setEnabledWithNSNumber:) withObject:[NSNumber numberWithBool:YES]];

NSArray makeObjectsPerformSelector example.
int main (int argc, char** argv)
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

    Card* two = [[Card alloc] initValue:2 withSuit:'d'];
    NSLog(@"Current retain count for the '2' Card: %ud", [two retainCount]);

    Card* three = [[Card alloc] initValue:3 withSuit:'h'];
    Card* four = [[Card alloc] initValue:4 withSuit:'c'];
    NSArray* deck = [NSArray arrayWithObjects:two,three,four,nil];

    NSLog(@"Current retain count for the '2' Card after array retains it: %ud", [two retainCount]);

    [two release];
    [three release];
    [four release];

    NSLog(@"Current retain count for the '2' Card after releasing instance: %ud", [two retainCount]);

    [deck makeObjectsPerformSelector:@selector(displayCard)];

    [deck release];
    NSLog(@"Current retain count for the '2' Card after releasing instances within 'deck' array: %ud", [two retainCount]);

    [pool release];

    return 0;
}

End of NSArray makeObjectsPerformSelector example article.