How to wrap a Struct into NSObject

后端 未结 3 676
滥情空心
滥情空心 2020-11-30 22:18

this is supposed to be trivial… I think, but I can\'t find a way how to wrap a Struct variable into an NSObject. Is there a method to do so? If not, how would I

3条回答
  •  無奈伤痛
    2020-11-30 23:10

    Something like like this would be the category @Rpranata is talking about :)

    struct _Pair
    {
        short val;
        short count;
    };
    typedef struct _Pair Pair;
    
    @interface NSValue (Pair)
    + (id)valueWithPair:(Pair)pair;
    - (Pair)pairValue;
    @end
    
    @implementation NSValue (Pair)
    + (id)valueWithPair:(Pair)pair
    {
        return [NSValue value:&pair withObjCType:@encode(Pair)];
    }
    - (Pair)pairValue
    {
        Pair pair; [self getValue:&pair]; return pair;
    }
    @end
    

    Usage:

    // Boxing
    Pair pair; pair.val = 2; pair.count = 1;
    NSValue *value = [NSValue valueWithPair:pair];
    
    // Unboxing
    NSValue value = ...
    Pair anotherPair = [value pairValue];
    

提交回复
热议问题