Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Box Custom Struct in Objective-C [duplicate]

Possible Duplicate:
How to wrap a Struct into NSObject
Can the new Clang Objective-C literals be redirected to custom classes?

I have a custom struct:

typedef struct {
    float f1;
    float f2;
} MYCustomStruct;

that I need to add to an NSArray. I've already written a category to create NSValues of these structs, which I then add to the NSArray, however I'd like to simplify that even further using boxed expressions, if possible. I'd love to be able to do this:

@[@(instanceOfMYCustomStruct)];

however, I'm confronted with the following error:

Illegal type 'MYCustomStruct' used in a boxed expression

Is there a way to use boxed expressions with custom structs?

like image 617
Patrick Perini Avatar asked Oct 29 '12 16:10

Patrick Perini


1 Answers

I would use a NSValue to box a struct, as it has built-in support for it. Unfortunately, you cannot use objective-c's cool literals for it, though:

struct foo myStruct;
NSValue *val = [NSValue valueWithBytes:&myStruct objCType:@encode(typeof(myStruct))];

// to pull it out...
struct foo myStruct;
[val getValue:&myStruct];

While this may be unwieldy & ugly amidst other objc code, you have to ask yourself - why are you using a struct in the first place in Objective-C? There are few speed performances gained over using an object with a few @property(s), the only real reason I could see is if you are integrating with a C library for compatibility with memory layouts, and even then, the structure of an objective-c object's memory layout is well-defined, so long as the superclass doesn't change.

So what is your real purpose in boxing a struct? If we have that, we can help you further.

like image 150
Richard J. Ross III Avatar answered Oct 20 '22 19:10

Richard J. Ross III