How to conditionally use the new Cocoa API

In 10.6, Apple added +[NSPropertyListSerialization dataWithPropertyList:format:options:error:] and is marked as old +[NSPropertyListSerialization dataFromPropertyList:format:errorDescription:] as deprecated and soon deprecated. One way to use the new call on 10.6 and above and still run on earlier versions of the OS would look something like this:

 if ([NSPropertyListSerialization respondsToSelector:@selector(dataWithPropertyList:format:options:error:)]) { data = [NSPropertyListSerialization dataWithPropertyList:dict format:NSPropertyListXMLFormat_v1_0 options:0 error:&err]; } else { data = [NSPropertyListSerialization dataFromPropertyList:dict format:NSPropertyListXMLFormat_v1_0 errorDescription:&errorDescription]; } 

Built against the 10.4 SDK (for compatibility with this version), this leads to: warning: 'NSPropertyListSerialization' may not respond to '+dataWithPropertyList:format:options:error:' And even worse, since the compiler does not know about this selector, it may pass arguments incorrectly.

Is NSInvocation an approved / best way to call new APIs that do not yet exist with respect to the SDKs?

+4
source share
2 answers

Another way to do this is to declare the missing method yourself as a category of the class in question. This will cause the compiler to stop complaining that it will not find the method, although of course you still need to check the execution that you already do to avoid calling the method. You might also want to wrap such an ad with accessibility macros so that it is ignored after switching to using the 10.5 / 10.6 SDK and you will not get another compiler complaint in line. It will look something like this:

 #if MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4 //ignore when compiling with the 10.5 SDK or higher @interface NSPropertyListSerialization(MissingMethods) + (NSData *)dataWithPropertyList:(id)plist format:(NSPropertyListFormat)format options:(NSPropertyListWriteOptions)opt error:(NSError **)error; @end #endif 
+2
source

IIRC, you want to use the 10.6 SDK and set the deployment target (MACOSX_DEPLOYMENT_TARGET) to 10.4 so that the 10.5 / 10.6 characters are loosely coupled. Then you can use the respondsToSelector: material and not receive warnings.

Make sure you verify that the object can respond to the selector, of course, or you will crash 10.4 / 10.5.

+6
source

All Articles