Sunday, May 19, 2013

NSString rangeOfComposedCharacterSequenceAtIndex example ios

[NSString rangeOfComposedCharacterSequenceAtIndex]

Returns the range in the receiver of the composed character sequence located at a given index.
- (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)anIndex
The index of a character in the receiver. The value must not exceed the bounds of the receiver.
Return Value of [NSString rangeOfComposedCharacterSequenceAtIndex]
The range in the receiver of the composed character sequence located at anIndex.
The composed character sequence includes the first base character found at or before anIndex, and its length includes the base character and all non-base characters following the base character.
Example of [NSString rangeOfComposedCharacterSequenceAtIndex]
@interface NSString (UTF)

- (NSRange) rangeOfUTFCodePoint:(NSUInteger)number;


@implementation NSString (UTF)

- (NSRange) rangeOfUTFCodePoint:(NSUInteger)number
    NSUInteger codeUnit = 0;
    NSRange result;
    for(NSUInteger ix = 0; ix <= number; ix++)
        result = [self rangeOfComposedCharacterSequenceAtIndex:codeUnit];
        codeUnit += result.length;
    return result;

Example of [NSString rangeOfComposedCharacterSequenceAtIndex]
@interface NSString (ConvertToArray)
-(NSArray *)convertToArray;

@implementation NSString (ConvertToArray)

- (NSArray *)convertToArray {
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    NSUInteger i = 0;
    while (i < self.length) {
        NSRange range = [self rangeOfComposedCharacterSequenceAtIndex:i];
        NSString *chStr = [self substringWithRange:range];
        [arr addObject:chStr];
        i += range.length;

    return arr;


NSArray *array = [@"Hello 😄" convertToArray];
NSLog(@"array = %@", array);
Example of [NSString rangeOfComposedCharacterSequenceAtIndex]
NSUInteger lastCharIndex = [myString length] - 1; // I assume string is not empty
NSRange rangeOfLastChar = [myString rangeOfComposedCharacterSequenceAtIndex: lastCharIndex];
myNewString = [myString substringToIndex: rangeOfLastChar.location];