0

If it matters I need this particularly when self is a UIView subclass. By way of example to clarify my question, the following stmt:

NSLog(@"self: %@", self);

gives the following output:

<RCLDataView: 0x10971a0b0; frame = (0 0; 0 0); transform = [0, 0, 0, 0, 0, 0]; alpha = 0; opaque = NO; layer = (null)>

I want just that address (0x10971a0b0) without the rest of the text. I suppose I can (somehow) capture that full string and (somehow) extract the address with NSString methods. But that seems really ugly. There is probably a way to get the address directly, since NSLog can get it.

RobertL
  • 14,214
  • 11
  • 38
  • 44
  • 8
    See the docs for format specifiers. You want `%p`. – rmaddy Jul 14 '14 at 03:51
  • 4
    `%@` says use the `description` method of the argument (if it has none, it will use the default `NSObject` implementation) As @rmaddy said, you want to use a different format specifier, specifically `%p` – Chris Wagner Jul 14 '14 at 04:09

1 Answers1

4
NSString *addressString = [NSString stringWithFormat:@"%p", yourString];

unsigned long long address = 0;
NSScanner *scanner = [NSScanner scannerWithString:addressString];

[scanner scanHexLongLong:&address];
NSLog(@"%llx", address); //Prints the address

The first line gets the pointer address and puts it into an NSString. The next line instantiates an unsigned long long to hold the hex value of the pointer. The pointer address representation is 64 bits I think so we need a 64 bit value to hold it. I know an int is not large enough but a long long works. Alternatively you could use a uint64_t depending on your architecture. The next two lines are to extract the hex value and store it in our long long. The NSScanner method is the only way I know to get a hex value from an NSString so I just used that. The last line of course is to print the value to make sure it's correct. You can check if it's correct by also printing the addressString.

Milo
  • 5,041
  • 7
  • 33
  • 59
  • What is hexInt? It looks like something was left out here. Don't I just want addressString as the result? – RobertL Jul 15 '14 at 01:12
  • @RobertL That was a mistake I made when I was testing out the above code. And as for addressString, it depends on what you want to use the address for. If you're using it in any kind of C function and it requires an address parameter or something then you need a primitive value of the address as you can't pass in Objective-C objects like NSString. – Milo Jul 15 '14 at 01:50
  • Please don't just dump code as an answer. Add a description too. – Lee Taylor Jul 15 '14 at 02:01
  • `unsigned long long` will work, of course, but there is actually a type -- `uintptr_t` -- that is defined to be big enough to hold an address, whatever the size is on the current architecture. There's also apparently a [`printf()`/`scanf()` format macro for this size](http://stackoverflow.com/a/12228414/603977). – jscs Jul 16 '14 at 04:01