views:

89

answers:

2

This is probably a naive question but, how do I get the length of the stringValue of an NSTextField? I tried

int len = strlen((char *)[textField stringValue]);

where textField is an NSTextField but it always returns 6 (size of a pointer?). Besides I am sure that there is a more Objective-C way to do what I am after.

+7  A: 

See NSString documentation

NSUInteger length = [[textField stringValue] length];

The crucial thing to realize here is that an NSString is not a char*. To get a real C-style char*, you need to do something like:

const char* ptr = [[textField stringValue]
    cStringUsingEncoding:[NSString defaultCStringEncoding]];

Updated to use default encoding instead of assuming ASCII.

nall
just nitpicking, but using NSASCIIStringEncoding is more dangerous than simply passing a zero, which will give you the default encoding.regardless, +1
kent
Good point. I didn't find the 0 thing documented anywhere, so I went the explicit route.
nall
+2  A: 

stringValue is NSString instance. You may use the next code:

NSUInteger len = [[textField stringValue] length];
Pavel Yakimenko