Friday, May 31, 2013

NSArray makeObjectsPerformSelector withObject example in Objective C (iOS).


NSArray makeObjectsPerformSelector withObject

Sends the aSelector message to each object in the array, starting with the first object and continuing through the array to the last object.

- (void)makeObjectsPerformSelector:(SEL)aSelector withObject:(id)anObject

Parameters
aSelector
A selector that identifies the message to send to the objects in the array. The method must take a single argument of type id, and must not have the side effect of modifying the receiving array.
anObject
The object to send as the argument to each invocation of the aSelector method.

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

NSArray makeObjectsPerformSelector withObject example.
for (id delegate in _delegates)
   [delegate modelDidFinishLoad:self];
or even easier, using NSArray's -makeObjectsPerformSelector:…:

[_delegates makeObjectsPerformSelector:@selector(modelDidFinishLoad:)
                            withObject:self];

Example of [NSArray makeObjectsPerformSelector withObject].
@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 withObject 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 withObject example article.