1

I've seen this, but there needs to be an easier way than that.

If I have an array of NSNumbers and I want to increment one of them, I have to do this?

[myMutableArray replaceObjectAtIndex:index withObject:[NSNumber numberWithInt:[(NSNumber *)[myMutableArray objectAtIndex:index] intValue] + 1]];

or

myArray = [myArray.mutableCopy replaceObjectAtIndex:index withObject:[NSNumber numberWithInt:[(NSNumber *)[myArray objectAtIndex:index] intValue] + 1]].copy;

if you decide to use an immutable array for some reason.

I know I could always just use an int array, but I was just curious if there was a simple way to do this.

Also, how should I define an int array if I need access to it either within an implementation or a full file (the entire .m) without making it global?

Would it just be as simple as throwing this at the top of my implementation / file?

static int *myInt;
Community
  • 1
  • 1
RileyE
  • 10,874
  • 13
  • 63
  • 106

2 Answers2

3

As others said, yes, you need that many steps. With literals, it can be a little easier to read:

myMutableArray[index] = @( [ myMutableArray[index] intValue] + 1 ) ;

Your second code example won't work because replaceObjectAtIndex:withObject: returns void, not the NSMutableArray it acted upon. You'd need to create a mutableCopy of the NSArray, then replaceObject, then set the NSArray to a copy of the NSMutableArray.

John Sauer
  • 4,411
  • 1
  • 25
  • 33
0

I would recommend using C++ STL containers rather than creating a plain int array if you need to be able to resize it. Rename your implementation file's extension to .mm instead of .m.

std::vector<int> numbers = { 2, 4, 6 };
numbers[1]++; // { 2, 5, 6 }

Remember to include the container's definition.

#import <vector>
Anurag
  • 140,337
  • 36
  • 221
  • 257
  • The reason I would use the vector is so that I don't have to deal with the malloc and free parts? For this situation, I don't need to resize the array, but just have free reign on changing the values. I would still be interested in knowing why the vector is better, if theres an actual performance increase, or whatnot. – RileyE Dec 30 '12 at 21:19