Tuesday, May 14, 2013

NSString getCharacters example ios


getCharacters: range:

Copies characters from a given range in the receiver into a given buffer.
- (void)getCharacters:(unichar *)buffer range:(NSRange)aRange
Parameters
buffer
Upon return, contains the characters from the receiver. buffer must be large enough to contain the characters in the range aRange (aRange.length*sizeof(unichar)).
aRange
The range of characters to retrieve. The range must not exceed the bounds of the receiver.

Important: Raises an NSRangeException if any part of aRange lies beyond the bounds of the receiver.
Discussion of [NSString getCharacters]
This method does not add a NULL character.
The abstract implementation of this method uses characterAtIndex: repeatedly, correctly extracting the characters, though very inefficiently. Subclasses should override it to provide a fast implementation.
Example of [NSString getCharacters]
void myFunc(NSString* data)
{
    NSUInteger len = [data length];
    unichar *buffer = calloc(len, sizeof(unichar));

    if (!buffer) return;

    [data getCharacters:buffer range:NSMakeRange(0, len)];

    for (NSUInteger i = 0; i < len; i++)
        NSLog(@"%04x", (unsigned) buffer[i]);

    free(buffer);
}
Example of [NSString getCharacters]
NSUInteger length = [str length];
unichar buffer[length];

[str getCharacters:buffer range:NSMakeRange(0, length)];

for (NSUInteger i = 0; i < length; i++)
{
    doSomethingWithThis(buffer[i]);
}
Example of [NSString getCharacters]
NSUInteger i, length = [string length];
unichar *buffer = malloc(sizeof(unichar) * length);
NSRange range = {0,length};
[string getCharacters:buffer range:range];
for(i = 0; i < length; ++i) {
    unichar c = buffer[i];
}