iOS — get pointer from NSString containing address

后端 未结 5 482
名媛妹妹
名媛妹妹 2021-01-01 02:57

If I have a pointer to an object foo with address (say) 0x809b5c0, I can turn that into an NSString by calling

NSString* fooString = [NSString stringWithForm         


        
相关标签:
5条回答
  • 2021-01-01 03:33

    Convert it to an integer, then cast it to whatever type it's supposed to be...

    NSUInteger myInt = [ myStr integerValue ];
    char * ptr       = ( char * )myInt;
    

    That said, I really don't understand why you will need this...

    0 讨论(0)
  • 2021-01-01 03:33

    In its completeness...

    To address-string

    NSString *foo = @"foo";
    NSString *address = [NSString stringWithFormat:@"%p", foo];
    

    And back

    NSString *fooAgain;
    sscanf([address cStringUsingEncoding:NSUTF8StringEncoding], "%p", &fooAgain);
    
    0 讨论(0)
  • 2021-01-01 03:45

    This snippet worked for me:

    NSString *pointerString = @"0x809b5c0";
    NSObject *object;
    sscanf([pointerString cStringUsingEncoding:NSUTF8StringEncoding], "%p", &object);
    
    0 讨论(0)
  • 2021-01-01 03:46

    Use an NSMapTable instead:

    MyClass* p = [[MyClass alloc]init];
    NSMapTable* map = [NSMapTable mapTableWithKeyOptions:NSMapTableStrongMemory valueOptions:NSMapTableStrongMemory];
    [map setObject:whateverValue forKey:p];
    // ...
    for(MyClass* key in map) {
    // ...
    }
    
    0 讨论(0)
  • 2021-01-01 03:51

    In my experience its easier to convert the pointer's address to an NSInteger, like this:

    MyObject *object=[[MyObject alloc]init];
    //...
    NSInteger adress=(NSInteger)object;
    

    Now reverse:

    MyObject *otherObject=(MyObject*)adress;
    

    Now: object==otherObject

    0 讨论(0)
提交回复
热议问题