How to wrap a Struct into NSObject

后端 未结 3 666
滥情空心
滥情空心 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 22:57

    Hm, try to look at the NSValue at https://developer.apple.com/documentation/foundation/nsvalue

    You can use it like

    struct aStruct
    {
        int a;
        int b;
    };
    typedef struct aStruct aStruct;
    

    Then sort of "wrap" it to an NSValue object like:

    aStruct struct; struct.a = 0; struct.b = 0;
    NSValue *anObj = [NSValue value:&struct withObjCType:@encode(aStruct)];
    NSArray *array = @[anObj];
    

    To pull the struct out from NSValue use:

    NSValue *anObj = [array firstObject];
    aStruct struct;
    [anObj getValue:&struct];
    

    I guess later on, you can have a category from NSValue to make that better =D

    0 讨论(0)
  • 2020-11-30 23:07

    Use + (NSValue *)valueWithCGAffineTransform:(CGAffineTransform)transform;

    From the docs: "Creates a new value object containing the specified CoreGraphics affine transform structure."

    CGAffineTransform fooAffineTransform = CGAffineTransformMakeScale(.5, .5);
    [NSValue valueWithCGAffineTransform:fooAffineTransform];
    

    +valueWithCGAffineTransform has existed since iOS 2.0.

    0 讨论(0)
  • 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];
    
    0 讨论(0)
提交回复
热议问题