Tuesday, May 14, 2013

NSString getCString maxLength encoding example ios


[NSString getCString maxLength encoding]

Converts the receiver’s content to a given encoding and stores them in a buffer.
- (BOOL)getCString:(char *)buffer maxLength:(NSUInteger)maxBufferCount encoding:(NSStringEncoding)encoding
Parameters
buffer
Upon return, contains the converted C-string plus the NULL termination byte. The buffer must include room formaxBufferCount bytes.[NSString getCString maxLength encoding]
maxBufferCount
The maximum number of bytes in the string to return in buffer (including the NULL termination byte).
encoding
The encoding for the returned C string.
Return Value of [NSString getCString maxLength encoding]
YES if the operation was successful, otherwise NO. Returns NO if conversion is not possible due to encoding errors or if buffer is too small.
Discussion of [NSString getCString maxLength encoding]
Note that in the treatment of the maxBufferCount argument, this method differs from the deprecatedgetCString:maxLength: method which it replaces. (The buffer should include room for maxBufferCount bytes; this number should accommodate the expected size of the return value plus the NULL termination byte, which this method adds.)
You can use canBeConvertedToEncoding: to check whether a string can be losslessly converted to encoding. If it can’t, you can use dataUsingEncoding:allowLossyConversion: to get a C-string representation using encoding, allowing some loss of information (note that the data returned by dataUsingEncoding:allowLossyConversion: is not a strict C-string since it does not have a NULL terminator).
Example of [NSString getCString maxLength encoding]
char command[512];
if(![theString getCString:command maxLength:sizeof(command)/sizeof(*command) encoding:NSUTF8StringEncoding]) {
    NSLog(@"Command buffer too small");
}
Example of [NSString getCString maxLength encoding]
NSUInteger len = [originalFeed lengthOfBytesUsingEncoding: NSUTF8StringEncoding] + 1;
char entireFeed[len];
[originalFeed getCString:entireFeed maxLength:len encoding:NSUTF8StringEncoding];
Example of [NSString getCString maxLength encoding]
BOOL success = [myCocoaString getCString:myData.USERNAME maxLength:32 encoding:NSUTF8StringEncoding];
NSLog(@"Was %@ to store string contents in USERNAME!", success ? @"able" : @"not able");