views:

155

answers:

4

Hi guys,

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 build an array that contains an NSInteger associated to an NSBool. I know I could use an array with each entry being a NSDictionary with a single key-value but I find it to be a little overkill.

Any ideas?

Thanks.

+2  A: 

You can use the STL in Objective-C++. All you need to do is change the extension of your .m file to .mm and I would also advise you use #import instead of #include. That way you can use your pair STL container.

thyrgle
Just keep in mind that STL containers do not `retain` and `release` objects.
dreamlax
thanks, it worked just fine. I'm surprised I didn't hear about this before.
omegatai
@omegatai: Will you please accept my answer then?
thyrgle
@omegatai: Thnx!
thyrgle
A: 

You can write your own data structure object - for such a simple case, it would be pretty easy:

@interface Pair : NSObject 
{
    NSInteger integer;
    BOOL      boolean;
}
@property (nonatomic, assign) integer;
@property (nonatomic, assign) boolean;
@end

And a matching implementation, then you stick your Pair objects into the NSArray problem free.

Carl Norum
@Martin, absolutely true. But the OP seems to indicate that he wants a specific pair. Replacing the two properties here with `id` would get the job done.
Carl Norum
A: 

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 <objc/runtime.h>

@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];
Kendall Helmstetter Gelner
A: 

Using anonymous struct and struct literals, you might be able to do something like

NSValue * v = [NSValue valueWithBytes:(struct {NSInteger i; bool b;}){i,b} objCType:(struct {NSInteger i; bool b;})];

and then to read,

struct {NSInteger i; bool b;} foo;
[v getValue:&foo];

It's a bit cleaner if you name your struct though.

tc.