Reasons to use NSString constants over enums?

coding-style, objective-c

Solution

I'm not sure, but I'm guessing it has to do with users adding their own extensions and subclasses to some of the Apple stuff. In that case, you can just override the used method and catch the case where the string is "MyOwnValue" and then do whatever you want with it. This is significantly easier than having to modify Apple's enum, and it also keeps you from screwing anything up.

It also might be for making it easier for Apple to have version independence. With enums, if you rearrange their order in some way it can cause a lot of problems for any of their values that have been cached (for whatever reason). If the enum's value is 1 << 3 when it is saved to a file, then Apple adds another enum in so that its value is now 1 << 4, then obviously the wrong thing is coming out of your program. Why wouldn't they just be careful about moving enum values around, I don't know, but I think it's definitely likely that they used NSString because there's no way its value or ordering can be changed across any version.

Problem

I'm wondering why Apple is using (quite heavily in CoreAnimation, but elsewhere too) constants that are declared as `NSString * const` like for example `kCAGravityTop` instead of regular enums? How about type safety in this case? As I understand it, one could pass any NSString to a method expecting this constant without getting any compiler warnings.

Original source