Search code examples
iosiphonensvalue

How to create an NSValue from the addition of a pointer and an integer?


I need to create a key for an NSMutableDictionary. The ideal key would be the merger of a pointer and an integer.

This will work for just the pointer NSValue *key = [NSValue valueWithPointer:somePointer];

How do I add together somePointer + someInt and then form a key from the result?


Solution

  • I would do this:

    NSObject *p = <object>
    int  n = 0xdeadbeef;
    NSValue *v = [NSValue valueWithPointer:(void *)((uint32_t )p + n)];
    
    NSLog(@"p = %p n = %x v = %@",p,n,v);
    

    Pointers are integer types whose size depends on your platform (32 or 64 bits typically) which can be added to other integral types using a suitable cast. Just make sure to cast with a type whose length is greater than or equal to the length of a void pointer. This will ensure that you don't truncate the pointer.