[Patch][ObjC][Proposal] NSValue literals

AlexDenisov 1101.debian at gmail.com
Mon Dec 1 03:07:25 PST 2014

Just a small update.
On the weekend I was thinking how to make the implementation better and ended up with another solution:
The easiest way to add support for the whole supported by NSValue structures is to check if NSValue has a class method named ‘valueWith<StructureName>’ (e.g. valueWithCGSize, valueWithCGVector), but with exceptions for NSGeometry (NSRect -> valueWithRect, NSPoint -> valueWithPoint).
The idea has a side effect: it could be extended to support some end-user structures just by defining a structure and adding a class method as a category to NSValue (with particular implementation), e.g.:

typedef struct _UserDefinedStruct {
// ...
} UserDefinedStruct;

@interface NSUserDefinedValue : NSValue 
- (instancetype) initWithUserDefinedStruct:(UserDefinedStruct)struct;

@interface NSValue (NSUserDefinedValue)
+ (NSValue *)valueWithUserDefinedStruct:(UserDefinedStruct)struct;

@implementation NSValue (NSUserDefinedValue)
+ (NSValue *)valueWithUserDefinedStruct:(UserDefinedStruct)struct {
	return [[NSUserDefinedValue alloc] initWithUserDefinedStruct:struct];
// …

UserDefinedStruct s;
NSValue *v = @(s);

Though, it has a drawbacks as well, let’s consider that SomeStruct is defined, but NSValue is not included into translation unit, so this code

SomeStruct s;
id value = @(s);

will produce the error ’NSValue must be available to use Objective-C literals’ instead of expected 'illegal type 'SomeStruct' (aka 'struct _SomeStruct') used in a boxed expression’ which is not very helpful.

Initial implementation is more strict and less flexible, it is able to support only currently known structures, which means that compiler should be adopted for each new version of SDK (if new structures appear).
Second implementation (valueWith<StructName>) is more flexible, because it doesn’t require to hardcode all the currently supported structures, also it extensible by the end user (like NSArray/NSDictionary subscripting) which might be helpful in some cases. On the other hand: it looks error prone, so I’m not sure if it’s a good idea.

I would really appreciate any feedback.
Please, let me know if you need additional information.
Software Engineer, https://github.com/AlexDenisov

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20141201/e9637958/attachment.html>

More information about the cfe-commits mailing list