13.07.2015 Views

Beginning Objective-C pdf - EBook Free Download

Beginning Objective-C pdf - EBook Free Download

Beginning Objective-C pdf - EBook Free Download

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

66CHAPTER 3: Foundational APIsNote If you choose to use ARC in your project, you will see compiler warnings for every use of-performSelector: as the compiler doesn’t know the reference-counting characteristics of the APIyou’re calling at this point. The best solution to this warning we’ve found is to use NSInvocation toimplement the method call instead.Listing 3-43 provides an example of how to add a method to the NSObject class.Listing 3-43. Adding an Instance Method at Runtime#import id myNewMethod (id self, SEL _cmd){NSLog(@"I was added at runtime!");}void installMyMethod(void){IMP implementation = (IMP)myNewMethod;SEL selector = sel_registerName("myNewMethod");// We need a string defining the return and argument types for the method// Let's copy one from another (void) -noArgs method somewhere.Method from = class_getInstanceMethod([NSObject class], @selector(dealloc));const char *types = method_getTypeEncoding(from);}// add the new methodclass_addMethod([NSObject class], selector, implementation, types);// it's also possible to add a method based on a Block:selector = sel_registerName("myBlockMethod");implementation = imp_implementationWithBlock(^{ NSLog(@"I'm a block method!"); });class_addMethod([NSObject class], selector, implementation, types);NSObject *object = [[NSObject alloc] init];[object myNewMethod]; //prints "I was added at runtime!" to the debug console[object myBlockMethod]; // prints "I'm a block method!" to the debug consoleAs you can see, the code to add new methods to classes at runtime is very low level comparedto most of <strong>Objective</strong>-C.Making It UsefulYou could be forgiven for wondering just how useful this is. So here’s a prime example: supporting old and new APIsin the same code.Let’s say that you’re using a system class that has a useful API in the latest OS X or iOS version, but you have tosupport older versions, too. You have your own implementation of the same function, but it’s fairly slow, and you’dwww.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!