Prolific use of strings for state in Cocoa frameworks

Originator:kusterer
Number:rdar://13594403 Date Originated:07-Apr-2013 02:27 PM
Status:Open Resolved:
Product:iPhone SDK Product Version:10.8.3
Classification:Enhancement Reproducible:Not Applicable
 
A lot of the Cocoa APIs use NSStrings to indicate state. However, these strings are private constants that are not supposed to be looked at, their contents relied on, or saved to disk. This means that anyone who wants to keep a record of their state or wants to perform different actions based on state has to write chains of 'if' statements.

The surface fix for this would be to add support for objects to the switch() statement in ObjC, so one can switch like:

switch( exportSession.exportPreset )
{
	case AVExportPresetIPad:
		// react.
		break;
}

An even better fix would be to allow to dispatch on string identifiers in some better way that maps a preset to a selector. I *can* do this with strings whose contents are guaranteed, where I can use NSSelectorFromString() to build a selector based on its contents. Another alternative would be to fix the frameworks to use real objects (on which one can declare categories that will dispatch to the right place) instead of string constants. For this I propose an @enum construct:

@enum
{
	AVExportPresetIPad,
	AVExportPresetIPhone
};

where each constant would effectively map to something like:

@interface AVExportPresetIPad : NSObject
@end

AVExportPresetIPad*	AVExportPresetIPad = [[AVExportPresetIPad alloc] init];

(Where the alloc/init would effectively be a global object like a class, not an actual heap object) People can now use this like any other object and class, and declare categories on it to add their specialized dispatch. Even better, for backward compatibility, one could add support for types in enums like that, like:

@enum : NSString
{
	AVExportPresetIPad = @"ExportPresetIPad",
	AVExportPresetIPhone = @"ExportPresetIPhone"
};

which would isa-swizzle the string to pretend to be an NSString subclass named like the constant, which means old code gets the same string, but new code can declare categories on it etc. Furthermore, it would be easy to graduate from constants to a full-blown object

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!