Equivalent of C++ STL container “pair” in Objective-C?

后端 未结 5 788
无人及你
无人及你 2021-02-13 03:34

I\'m new to Objective-C, so please don\'t judge me too much. I was wondering: Is there an equivalent of the C++ STL pair container I can use in Objective-C?

I want to bu

5条回答
  •  感情败类
    2021-02-13 04:04

    How about a Pair category on NSNumber that uses associated objects, something like the code below (untested, may require iOS4 as I'm not sure when associated objects were introduced).

    #import 
    
    @implementation NSNumber(Pair)
    
    #define PAIR_KEY 'p'
    
    - (NSNumber *) pairNumber:(NSNumber *)second
    {
        char secondKey = PAIR_KEY;
        objc_setAssociatedObject(self, &secondKey, second, OBJC_ASSOCIATION_RETAIN);
        return self;
    }
    
    - (NSNumber *) pairedNumber
    {
        char secondKey = PAIR_KEY;
        NSNumber *associatedObject = (NSNumber *)objc_getAssociatedObject(self, &secondKey);    
        return associatedObject;
    }
    
    @end
    

    You would use it like so:

    BOOL myBool = NO;
    
    NSNumber *storedBool = [NSNumber numberWithBool:myBool];
    
    [myOtherNumber pairNumber:storedBool];
    

    And to get it out:

    NSNumber *boolNumber = [myOtherNumber pairedNumber];
    

提交回复
热议问题