0

Why can I not access the 4th element of an NSMutableArray when I initialise with a NSString object rather than input the text manually?

For Example:

NSString * d = @"d";

self.arr = [[NSMutableArray alloc] initWithObjects:
          [NSMutableArray arrayWithObjects:@"A",@"B",@"C",d,nil],
          [NSMutableArray arrayWithObjects:@"A",@"B",@"C",@"d",nil],
           nil];

This causes a beyond bounds error (NSString):

NSMutableArray *subArray  = [self.arr objectAtIndex:0];
question = [subArray objectAtIndex:3];

This doesn't (@"d"):

NSMutableArray *subArray  = [self.arr objectAtIndex:1];
question = [subArray objectAtIndex:3];

Why does this happen? Surely they are the same thing? I was hoping to reduce the amount of times I would have to write @"d".

8
  • have you try with NSLog(@"%@",[[self.arr firstObject ]objectAtIndex:3]); Commented Dec 16, 2013 at 9:03
  • Is this for a quiz type of app? There are other ways you can store the answers. Commented Dec 16, 2013 at 9:04
  • 4
    This code worked perfect. There is no beyond bounds error. Commented Dec 16, 2013 at 9:06
  • This code looks good to me. One thing to try is to log the whole array and see if it's what you expect (NSLog(@"%@", self.arr)). It's possible that d isn't really set to what you think it is, and it's in fact nil at the time of array creation. Commented Dec 16, 2013 at 9:07
  • 2
    Clean your project, close and reopen Xcode. Run again. Commented Dec 16, 2013 at 9:11

1 Answer 1

1

They should be same... i tried following in my project. it works well.

NSString * d = @"d";

NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:
                [NSMutableArray arrayWithObjects:@"A",@"B",@"C",d,nil],
                [NSMutableArray arrayWithObjects:@"A",@"B",@"C",@"d",nil],
                nil];

NSLog(@"0 array 4th:%@",[[array objectAtIndex:0] objectAtIndex:3]);
NSLog(@"1 array 4th:%@",[[array objectAtIndex:1] objectAtIndex:3]);

output is as followings:

2013-12-16 17:05:30.092 Demo[1005:60b] 0 array 4th:d
2013-12-16 17:05:30.094 Demo[1005:60b] 1 array 4th:d
Sign up to request clarification or add additional context in comments.

Comments

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.