0

I am getting below response into the nsarray when I used the JSON parsing from my required URL but here I don't like to get 2,1,4,4,6,5,8,7,10,9,12 and 11 in single array I have to get total response into two arrays I mean one array set will consists 2,4,6,8,10 and other array set must be 3,5,7,9 and 11.

So how is the code for separation of single array response into two arrays in iPhone?

"(\n    2,\n    1\n)",
"(\n    4,\n    3\n)",
"(\n    6,\n    5\n)",
"(\n    8,\n    7\n)",
"(\n    10,\n    9\n)",
"(\n    12,\n    11\n)"
1
  • Are either of the answers what you needed? If so, please mark one as correct. Or if not, maybe we didn't understand the question. Is the text with the parentheses, spaces, and newline codes part of your explanation, or do you need to parse out those extra characters to get to the numbers? Commented May 30, 2012 at 0:35

2 Answers 2

5

If you combine every number into one large array, you could feasibly test if each number is even or odd with a simple if-else in a for-in loop. Maybe like this:

-(NSArray*)parseJSONIntoArrays:(NSArray*)array {
    NSMutableArray *evenNumbers = [[NSMutableArray alloc]init];
    NSMutableArray *oddNumbers = [[NSMutableArray alloc]init];

    for (NSNumber *number in array) {
        if (([number intValue] %2) == 0) {
            //even
            [evenNumbers addObject:number];
        }
        else {
            //odd
            [oddNumbers addObject:number];
        }
    }
    return [[NSArray alloc]initWithObjects:evenNumbers, oddNumbers, nil];
}
Sign up to request clarification or add additional context in comments.

Comments

4

To split an array, you usually need to loop through all of the values and use an IF ELSE structure to decide which array to put the values in. Also, you need to use NSMutableArray instead of NSArray. Something like this:

NSMutableArray *evenNumbers = [NSMutableArray new];
NSMutableArray *oddNumbers = [NSMutableArray new];
for (NSNumber *value in myArray) {
    if ([value intValue] % 2 == 0) {
        [evenNumbers addObject:value];
    } else {
        [oddNumbers addObject:value];
    }
}

2 Comments

Dang! Beat me to it by a minute, oh, and NSInteger will throw a "not an object" warning from Xcode. you must use NSNumber, or this won't work.
Thanks @CodaFi. I fixed my example. I realize are multiple ways to do the test for even-numberedness, but this should work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.