iPhone Programming: NSInvocation - Storing Methods as objects

Опубликовано: 25 Октябрь 2024
на канале: MilmersXcode
944
15

In this tutorial I teach you what NSInvocation is and how to use it.

Main Code:

(void)viewDidLoad
{
[super viewDidLoad];
myArray = [[NSMutableArray alloc] init];
[self setUpInvocations];
[NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(logThis:andThis:) userInfo:nil repeats:NO];
}

(void)setUpInvocations
{
NSMethodSignature *sig1 = [self methodSignatureForSelector:@selector(logThis:andThis:)];
NSMethodSignature *sig2 = [NSMutableArray instanceMethodSignatureForSelector:@selector(addObject:)];
NSInvocation *inv1 = [NSInvocation invocationWithMethodSignature:sig1];
NSInvocation *inv2 = [NSInvocation invocationWithMethodSignature:sig2];
[inv1 setTarget:self];
[inv2 setTarget:myArray];
[inv1 setSelector:@selector(logThis:andThis:)];
[inv2 setSelector:@selector(addObject:)];

NSString *str = @"Twenty Five";
int i = 5;
NSString *array = @"Array String";

[inv1 setArgument:&str atIndex:2];
[inv1 setArgument:&i atIndex:3];
[inv2 setArgument:&array atIndex:2];

[inv1 invoke];
[NSTimer scheduledTimerWithTimeInterval:2 invocation:inv2 repeats:YES];
[NSTimer scheduledTimerWithTimeInterval:2 invocation:inv1 repeats:YES];
}

(void)logThis:(NSString *)str andThis:(int)i
{
NSLog(@"%@ + %i",str,i);
NSLog(@"%@",myArray);
}

Custom Methods Tutorial:    • iPhone Programming: Custom Methods wi...  

Twitter:   / failcakeapps  
Apple Developer Center: http://developer.apple.com/devcenter/...
Website: http://failcake.webs.com/
Channel:    / milmersxcode