简体   繁体   中英

Reverse an Array of String in Objective-C

I would like to reverse an array of string in Objective-C.

I know there is a in built-method of doing it as follows:

NSArray* reversedArray = [[inputString reverseObjectEnumerator] allObjects];

but I want to implement same functionality with coding as follows and getting the following error.

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {

    NSMutableArray *inputString = [NSMutableArray arrayWithObjects:@"a", @"b", @"c", @"d", @"e", @"f", @"g", @"h", @"i", nil];

        int lenArray= (int)[inputString count];

        NSMutableArray *reverseString=[[NSMutableArray alloc]initWithCapacity:lenArray];

        for(int i=lenArray-1;i>0;i--)
        {
            [reverseString insertObject:inputString[i] atIndex:i];
        }
      return 0;
    }
  }

Terminating app due to uncaught exception 'NSRangeException', reason: ' -[__NSArrayM insertObject:atIndex:]: index 8 beyond bounds for empty array'

[reverseString insertObject:inputString[i] atIndex:i]; is the problem - specifically the atIndex:i part. You've created your mutable array with a large enough capacity, however it is still empty so specifying the index here is not what you meant to do.

Instead, just use addObject: [reverseString addObject:inputString[i]];

Try this:

for (int i = lenArray-1; i >= 0; i--) {
    [reverseString addObject:inputString[i]];
}

Note: Just use addObject: and change your for-loop condition to i >= 0 , otherwise the "a" will be missing.

Enjoy!

Here is the complete solution:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {

        NSMutableArray *inputString = [NSMutableArray arrayWithObjects:@"a", @"b", @"c", @"d", @"e", @"f", @"g", @"h", @"i", nil];
      //  NSArray* reversedArray = [[inputString reverseObjectEnumerator] allObjects];

            int lenArray= (int)[inputString count];

            NSMutableArray *reverseString=[[NSMutableArray alloc]initWithCapacity:lenArray];

                for (int i = lenArray-1; i >= 0; i--) {
                    [reverseString addObject:inputString[i]];
                }

               for(int i=0;i<=lenArray-1;i++)
                {
                    NSLog(@"%@\n", [reverseString objectAtIndex:i]);
                }
    return 0;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM