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.

CHAPTER 3: Foundational APIs 67like to use the better version when that’s available. Or worse, perhaps the older API actually performs differently onolder systems (UIViewController.parentViewController, I’m looking at you).You could work around it by calling -respondsToSelector: everywhere in your code, but that’s not a gracefulway to handle it. Instead, you create two methods, like so:- (void) doSomething{// legacy code goes here. . .}- (void) doSomethingWithNewAPI{// do the same thing, but using the new API}Now, rather than selectively calling the appropriate method, you can just use the ObjC runtime to swap themaround—effectively to swap the contents of the two methods, so that -doSomething contains the code from-doSomethingWithNewAPI and vice versa. The <strong>Objective</strong>-C runtime even gives you a nice and simple one-shotfunction that does this for you. So, rather than checking for the new API at every potential call site, you can put itsomewhere like the object’s +initialize method (+initialize gets called by the runtime immediately beforethe first message dispatch is sent to a class), like so:+ (void) initialize{// this gets called for my class and all its superclasses, so check:if (self != [MyObject class] )return;if ( [[SomeSystemClass instancesRespondToSelector: @selector(theNewAPI)] == NO )return; // running the old system, leave the legacy code in place// get the two methods:Method legacy = class_getInstanceMethod(self, @selector(doSomething));Method newAPI = class_getInstanceMethod(self, @selector(doSomethingWithNewAPI));}// swap the implementations of those two methods:method_exchangeImplementations(legacy, newAPI);Now your newAPI code will run whenever you call -doSomething on a recent OS version, while the older versions willstill run the legacy code. Neat, huh?www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!