What if you want to build the iPhone app with iOS sdk 6.0 and want to use some method of iOS sdk 7.0?
There is no such way in Xcode to build the app using two different versions of iOS sdk.
If you use any method which is available only in iOS 7.0 and set base sdk 6.1 , Xcode will give you error on compile time. To avoid this error on compile time, I came across some excellent methods of Objective C like
- forwardingTargetForSelector, forwardInvocation and invocationWithMethodSignature
Let us suppose we want to use autoFocusRangeRestriction of UIDevice class which is available from iOS 7 and our app base sdk is set for iOS 6.1. Use the following lines of code.Your code will compile and work without any error.
AVCaptureDevice *device = [[self videoInput] device];
A selector is the name used to select a method to execute for an object, or the unique identifier that replaces the name when the source code is compiled. And this is best thing in Objective C .
SEL sel = @selector(setAutoFocusRangeRestriction:);
You can set any name in @selector and compiler will check only the unique name so your code will compile without any error
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[device methodSignatureForSelector:sel]];
[inv setSelector:sel];
[inv setTarget:device];
int AVCaptureAutoFocusRangeRestrictionFarValue = 2;
[inv setArgument:&AVCaptureAutoFocusRangeRestrictionFarValue atIndex:2];
[inv invoke];
So the code compiles without any error with iOS sdk 6.1 as compiler will check only the unique name of method. When the program runs on iOS 7, it will check presence of method by
if([device respondsToSelector:sel])
and it will work as this method is present in iOS 7.0 . Rest code will be handled by NSInvocation class object.
NSInvocation objects are used to store and forward messages between objects and between applications. An NSInvocation object contains all the elements of an Objective-C message: a target, a selector, arguments, and the return value. Each of these elements can be set directly, and the return value is set automatically when the NSInvocation object is dispatched.
0 Comment(s)