Reverse NSString with Objective-C

Objective-C ensure you more possibilities when you’re manipulating existing objects like NSArray, NSString, NSDictionary etc. Some API functions can be done less code and some other snippets really mess.

Here is the reverse string block code

NSString *myString = @"abcdefghijklmnopqrstuvwxyz";
NSMutableString *reversedString = [NSMutableString stringWithCapacity:[myString length]];

[myString enumerateSubstringsInRange:NSMakeRange(0,[myString length]) 
                             options:(NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences)
                          usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                            [reversedString appendString:substring];
                        }];

Before I learn reverse string block syntax I was doing this iterate trough all exist string length and after the range this string I was add these reversed string in a mutable array. Here is the my old approach

// first retrieve the text of textField1
NSString *myString = textField1.text;
NSMutableString *reversedString = [NSMutableString string];
NSInteger charIndex = [myString length];
while (myString && charIndex > 0) {
    charIndex--;
    NSRange subStrRange = NSMakeRange(charIndex, 1);
    [reversedString appendString:[myString substringWithRange:subStrRange]];
}
Advertisements