Support newer features in older versions of OS X SDK - objective-c

I've been learning more about Cocoa, Objective-C, and Xcode by contributing to an open-source project (IPMenulet); the project originally supported OS X 10.5.
In my haste, it seems that I have added features using SDK elements (NSJSONSerialization and the #autoreleasepool compiler directive) that aren't supported by the older SDK. Now, I'm trying to determine what if anything I can do to restore support for 10.5
Options:
NSJSONSerialization - I suppose that I could switch to JSONKit
#autoreleasepool {} - ?
#properties - add #synthesize and IVARs
Questions:
is there a way (compiler directives?) to use newer SDK elements if the OS supports it, switching to the older element if necessary? if so, is it better to refactor the functionality in version-specific methods (e.g. getJSONlegacy, getJSON)?
would it be better to mark the original project as a separate branch (to allow it to be enhanced)?

Different features involve different OS components, which defines how a feature can be used in multiple OS X versions. Here is my rough classification:
functionality is completely provided by some framework. For example, NSJSONSerialization is available in Mac OS X 10.7+. You can use the same solution for all OS versions or check at runtime if some functionality is available. For example,
if ([view respondsToSelector:#selector(setAcceptsTouchEvents:)])
[view setAcceptsTouchEvents:YES];
More details regarding multiple SDKs support can be found in SDK Compatibility Guide. Using SDK-Based Development.
functionality is completely provided by compiler. For example, #autoreleasepool, literals.
functionality is provided by compiler and runtime. For example, default #property synthesis. See Objective-C Feature Availability Index for more details.
functionality which depends on SDK against which an application is linked. It is more about behavior changes, such a mechanism is described in Backward Compatibility section in AppKit Release Notes.
And now back to your question. There is a mechanism to check in runtime if a feature is available, pretty often respondsToSelector: can do the job. I recommend to expose a single method which works on all OS versions. And only inside this method differences between OS versions are present. For example,
- (NSString *)base64EncodingForData:(NSData *)data {
NSParameterAssert(data);
if ([data respondsToSelector:#selector(base64EncodedStringWithOptions:)]) {
return [data base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength];
}
else {
// Manual encoding using <Security/SecEncodeTransform.h> and kSecBase64Encoding.
}
}
You can create some 1.1 maintenance branch, perform all work in master, and merge to maintenance branch only bugfixes. So from maintenance branch you'll release 1.1.1 and from master 1.2. It's a viable approach. But you cannot support Mac OS X 10.5 indefinitely, so you need to decide in which IPMenulet version you'll drop 10.5 support.

To the extent that it helps at all, the classic version of:
#autoreleasepool { ... code ... }
Was:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
... code ...
[pool drain];
drain is preferred to the normal release because it then all works properly with (also now deprecated) OS X garbage collection. But it counts as a release so there's no memory leak and you shouldn't also release.

Related

Why does objective-c not have API availability checking?

Swift 2 have API availability checking.
The compiler will give you an error when using an API too new for your
minimum target OS
Why can't the objective-c compiler do the equivalent?
I googled objective c API availability checking and only swift 2 results came out so I assume the compiler for objective c can't do that.
Xcode 9.0 brings the runtime availability checking syntax from Swift to Objective-C:
if (#available(macOS 10.9, *))
{
// call 10.9+ API
}
else
{
// fallback code
}
this comes complete with warnings for calling APIs that are newer than your deployment target (if those calls are not wrapped in checks).
finally ;)
The warning (Swift makes it an error) just hadn't been implemented in the Clang compiler for years, but it's not an inherent Objective-C limitation (although due to its dynamic nature, you won't be able to catch all cases), nor Swift terminology.
The Apple macros (e.g., NS_CLASS_AVAILABLE) and source attributes (__attribute__((visibility(...))), __attribute__((availability(...)))) to annotate headers with availability information have been there for years, and they are widely-used in Apple's SDKs. The macros are defined in Foundation's NSObjCRuntime.h, and the Availability.h/AvailabilityMacros.h system headers, and the compiler can (and does) read them.
In early 2015, the -Wpartial-availability warning has been added to Clang's master branch, but this commit/warning hadn't made its way into Apple's version of Clang until (including) Xcode 7.2. You will get an unknown warning option log when adding the warning flag to a project in Xcode 7.2, but the flag is available in Xcode 7.3. There's currently no predefined setting for it, but you can add the flag to Other Warning Flags under Build Settings.
There are other tools that use LLVM libraries to detect partially available APIs, e.g., Deploymate. For my diploma thesis, I developed a tool that integrates directly into Xcode and is based on a modification to the Clang compiler. The code is still online, but I haven't kept up with the general Clang development so it won't be of much use, except for learning purposes. However, the "official" code (linked above) is much cleaner and better.
Edit: Starting with Xcode 9, availability checking will work for Objective-C (and C), too. Instead of using the above-mentioned warning flag, which does not support raising the deployment target temporarily/locally and therefore causes plenty of false positives, there's -Wunguarded-availability, and if (#available(iOS 11, *)) {...} to check and raise the deployment target for the following block of code. It is off by default, but -Wunguarded-availability-new will be on by default, and starts checking anything beyond iOS/tvOS 11, watchOS 4, and High Sierra. More details on that can be found in the Xcode 9 beta release notes, which currently requires signing in with a developer account.
Objective C does not have availability checking as part of the language, as the same result is available via Objective C preprocessor.
That is the "traditional" way of doing that in C derived languages.
Want to know if compiled in debug mode?
#ifdef DEBUG
// code which will be inserted only if compiled in debug mode
#endif
Want to check at compile time for a minimum version?
Use the Availability.h header in iOS, and similar headers for Mac OS X.
This file reside in the /usr/include directory.
just test __IPHONE_OS_VERSION_MAX_ALLOWED with the preprocessor, e.g.:
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
if ([application respondsToSelector:#selector(registerUserNotificationSettings:)]) {
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert) categories:nil]];
}else{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert)];
}
#else
[[UIApplication sharedApplication] registerUserNotificationSettings: (UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert)];
#endif
As Swift does not have a preprocessor, they had to invent a way of doing these kind of checks within the language itself.
If you want to check availability of a method at runtime, please notice that the appropriate way is by using the method respondsToSelector:, or instancesRespondToSelector: (the latter at class level).
You will normally want to combine both approaches, compile time conditional compilation and runtime check.
Objective C method presence verification, e.g. at class level:
if ([UIImagePickerController instancesRespondToSelector:
#selector (availableCaptureModesForCameraDevice:)]) {
// Method is available for use.
// Your code can check if video capture is available and,
// if it is, offer that option.
} else {
// Method is not available.
// Alternate code to use only still image capture.
}
If you want to test if a C function exists at runtime, it is even simpler: if it exists, the function itself it is not null.
You can't use the same identical approach in both languages.
It does these days. Furthermore, with Xcode 11 (including the current Xcode 11.3.1), you can even get it from the snippets. Press the + button towards the top right of Xcode (as shown in the image below).
Then in the search box, type "API". All 3 versions of the snippet for API Availability Check will appear -- Objective C, C and Swift.
Of course, you will get errors in Objective-C code. But you won't find results in google for Objective-C, if you use a term defined for Swift as you will not find kisuaheli website in google if you search for a german word. ;-)
You will get an error linking Objective-C code against a too old SDK. This is simply because the used method or class or $whatever is not defined in the header for that SDK. Again, of course.
This is typical Swift marketing of Apple: Because of the incapability of Swift they have to extend the language to get something, which is quite easy in Objective-C. Instead of clarifying that this is the result of the poorness of Swift, they tell you that this is a great feature of Swift. It is like cutting your fingers and then saying: "We have the great plaster feature!!!!!!!!" And you have to wait only some days and one comes around on SO with the Q: "Why does Objective-C does not have the great plaster feature???????" The simple answer: It does not cut your fingers.
The problem is not to generate the errors. The problem is to have one source code for all versions, so you can simply change the SDK version and get new code (or errors). You need that for easier maintenance.
In Objective-C you simply can use the answer found here:
Conditionally Hide Code from the Compiler or you can do that at runtime as mentioned in the comments to the Q. (But this is a different solution of the problem by nature, because it a dynamic approach instead of a static one as you have to do in Swift.)
The reason for having a language feature in Swift is that Swift has no preprocessor, so the Objective-C solution would not work in Swift. Therefore conditional code would be impossible in Swift and they had to add the plaster, eh, language feature.

NSUUID conflict (iOS6.0 and Above)

We have a NSUUID class (we provide the declaration and implementation). We used it successfully up to iOS 6.0. We implemented it because UIDevice uniqueIdentifier was banned long before Apple deprecated it, and returning a NSUUID was a natural choice.
At iOS 6.0, we had to guard the define because Apple introduced the same class:
#if __IPHONE_OS_VERSION_MAX_ALLOWED <= __IPHONE_5_1
#interface NSUUID : NSObject {
...
}
#endif
iOS 5.1 and lesser are now broken. On iOS 5.1, we get back nil after alloc/init.
I tried to remove the #if/#end, but I get duplicate names when using the latest iPhone SDK.
Apple's lack of a stable API is a bug, not a feature. This "try it at runtime" crap is not cutting it. It makes it very difficult to write high integrity software.
From Tommy's response below, I can't instruct Apple's toolchain to use our implementation of NSUUID all the time. How do I provide an implementation of NSUUID for iOS 5.1 and lower (that might be compiled using the latest SDK)?
You can't. You've explicitly broken the rules:
Objective-C classes must be named uniquely [...] In order to keep
class names unique, the convention is to use prefixes on all classes.
You’ll have noticed that Cocoa and Cocoa Touch class names typically
start either with NS or UI. Two-letter prefixes like these are
reserved by Apple for use in framework classes.
You'll need to rename your own class. The quickest way is quite probably to right click on the class name, select "Refactor -> Rename..." and use a correct prefix this time. Xcode may not be able to refactor fully automatically since it'll obviously be ambiguous which NSUUID you're referring to in other parts of your code.
EDIT: regardless of grandstanding, if you want to implement code that provides a self-implemented replacement for NSUUID where it's not available then the solution is to "try it at runtime".
Assuming you've implemented NDRUUID, which implements the same interface as NSUUID then the quickest solution is to add something like this to your prefix header:
#define NSUUID (NSClassFromString(#"NSUUID") ? [NSUUID class] : [NDRUUID class])
You can then use [NSUUID UUID], etc, everywhere else in your code as though you were targeting iOS 6 only; the only difference is that when running under 5 you'll actually be addressing NDRUUID. Whenever you stop supporting 5 just remove that line from your prefix header and delete your own class from the project.
Hopefully you can see this is a much better way to handle introducing new APIs and backwards compatibility than, say, not using Apple's NSUUID at all anywhere until it's available everywhere.
I have built exactly what you asked for: an implementation of NSUUID for iOS 5.1 and lower that might be compiled using the latest SDK. See my NSUUID project on GitHub.

What is a non-fragile ABI?

It may seem implied that everyone knows what a "Non Fragile ABI" is - considering the frequency and matter-of-fact-nature to which it is referred to - within Xcode. For example...
Subscript requires size of interface node which is not constant in non-fragile ABI
or
Select the Objective-C ABI version to use. Available versions are 1 (legacy "fragile" ABI), 2, (non-fragile ABI 1), and 3 (non-fragile ABI 2).
That said... What is a non-fragile ABI? (and why isn't it called something less-abstract / explained more clearly?)
The non-fragile ABI refers to the ability to add instance variables to a class without requiring recompilation of all subclasses.
I.e. in v1 (there really aren't true versions of ObjC), if Apple were to add an instance variable to, say, NSView (on Cocoa, 32 bit), then every subclass of NSView (or subclass of subclass) would have to be recompiled or they would blow up. v2 and v3 fix this.
It is explained in detail in this weblog post.
The documentation you are referring to is in the llvm/clang man page. Pretty rare place to be for most developers most of the time; unless you are writing a Makefile that is driving the compiler directly, there isn't much reason to read that page (unless spelunking -- which is quite educational, of course).
It is written in the style of a Unix man page and, no surprise, is a bit... obtuse. For almost all tasks, it is best to stick to the higher level documentation. I.e. the Xcode build settings documentation is general quite a bit less obtuse.
After some poking around, one of the best summaries / pieces of advice on the subject is the following…
The non-fragile ABI allows for things like changing the ivars of a superclass without breaking already compiled subclasses (among other things). It's only supported on 64-bit on the Mac though, because of backwards compatibility concerns which didn't allow them to support it on existing 32-bit architectures.
It goes on to say, basically.. that if Xcode, which often is configured to build for the "Active Architecture Only", aka 64-bit only.. one may run into issues when switching to a "Release" scheme, which is usually set to build for both (63bit/32bit) architectures, aka "Universal"..
You may you want to use ARC on the Mac, I'm pretty sure you'll have to drop 32-bit support to do so. You can change the targeted architectures in the build settings for your target in Xcode.
In my own experience, I believe that what the non-fragile ABI benefits us with is an abbreviated syntax, and patterns such as…
// source.h - readonly public properties.
#interface SuperClassy : NSObject
#property (readonly) NSArray *cantTouchThis;
#end
// source.m set readonly properties, internally.
#implementation SuperClassy
// look, no #synthesize… just use _ivarName.
-(void) touchIt:(NSArray*)a { _cantTouchThis = a; }
#end
int main(int argc, const char * argv[]) {
SuperClassy *it = [SuperClassy new];
// you cannot set it.cantTouchThis = #[anArray].
[it touchIt:#[#"cats"]];
// but you can via a method, etc.
NSLog(#"%#", it.cantTouchThis);
}
NSLOG ➜ ( cats )

How to conditionally use a new Cocoa API

In 10.6 Apple added +[NSPropertyListSerialization dataWithPropertyList:format:options:error:] and labeled the older +[NSPropertyListSerialization dataFromPropertyList:format:errorDescription:] as obsolete and soon to be deprecated. One way to use the newer call on 10.6 and above, and still run on earlier OS releases, would be 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 that release), this results in: warning: 'NSPropertyListSerialization' may not respond to '+dataWithPropertyList:format:options:error:' And, worse, since the compiler does not know about this selector, it may pass the arguments incorrectly.
Is NSInvocation the approved/best way to call new APIs that, as far as the SDK is concerned, don't yet exist?
IIRC, you want to use the 10.6 SDK and set your deployment target (MACOSX_DEPLOYMENT_TARGET) to 10.4 so the 10.5/10.6 symbols are weak-linked. Then you can use the respondsToSelector: stuff and not get warnings.
Make sure you're checking that the object can respond to the selector, of course, or you will crash on 10.4/10.5.
One other way of doing things is to declare the missing method yourself as a category of the class in question. This will get the compiler to stop complaining about not finding the method, though of course you'll still need the runtime check you're already doing to avoid actually calling the method. You might also want to wrap such a declaration using availability macros, so that it will be ignored once you do move up to using the 10.5/10.6 SDK and you won't get a different compiler complaint down the line. That would 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

10.5 base SDK, 10.4 deployment: how to implement missing methods

I have a project that targets both Mac OS X 10.4 and 10.5, where 10.5 is the base SDK.
Some methods like -[NSString stringByReplacingOccurrencesOfString:withString] are unavailable in 10.4. I could just implement the functionality by hand. Another option would be to implement the method as a category, but that would mess with the 10.5 implementation and that's something I'd like to avoid.
So how do I implement such methods in 10.4 without messing up 10.5 and in such a way that I can take out the implementation easily when I decide to stop supporting 10.4?
I think you have to use +load and +initialize to load a method at runtime if the method doesn't already exists.
if ([myString respondsToSelector: #selector(stringByReplacingOccurrencesOfString:withString:)])
{
// 10.5 implementation
}
else
{
// 10.4 implementation
}
Use a category, but put a tag on the method name; for example, stringByReplacingOccurrencesOfString_TigerCompatible:. In the implementation, call either Leopard's implementation or your own.
When you go Leopard-only, do a project search for “TigerCompatible”, then burninate all of those methods and un-tag all of their call sites.
Put all the missing implementation in categories in a bundle which is loaded on startup in main() if running under Tiger.
How about using a C preprocessor macro to insert the relevant methods if it's being built for 10.4? Maybe try doing something like this in a category, so those methods which don't exist on 10.4 are only included if it's being built for 10.4?
#if defined(MAC_OS_X_VERSION_10_4) && MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4
// Put your implementations of the methods here
#endif
Do you need to support 10.4? If you're using 10.5 only methods in core parts of your app then it might be time to consider going 10.5 only.
Anyway, with the specific example given above, I suggest moving away from that and making a mutable copy of your string so you can use the similar method on NSMutableString which does work in 10.4