Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

1. Working with Objects > 1.8. Invoking the Selectors of an Object Dynamically

1.8. Invoking the Selectors of an Object Dynamically

Problem

You want to be able to dynamically call any method in any object given the name of the method and its parameters.

Solution

Use the NSInvocation class, like so:

- (NSString *) myMethod:(NSString *)param1
             withParam2:(NSNumber *)param2{

  NSString *result = @"Objective-C";

  NSLog(@"Param 1 = %@", param1);
  NSLog(@"Param 2 = %@", param2);

  return(result);
}

- (void) invokeMyMethodDynamically {

  SEL selector = @selector(myMethod:withParam2:);

  NSMethodSignature *methodSignature =
  [[self class] instanceMethodSignatureForSelector:selector];

  NSInvocation *invocation =
  [NSInvocation invocationWithMethodSignature:methodSignature];
  [invocation 

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint