1

I need to keep track of rows in sections in my UITableView. For this I want to create an array in which I put an amount of rows in each section. This array should be of a certain size - so I suppose it would be better to use NSArray instead of NSMutableArray.

My question is - how can I initialize it with a certain number of objects of type NSInteger initially set to 0? And how can I alter that array - in my particular case to increase value of each item when I need it?

For instance:

while (objects)
{
 myArray.(object string's first letter transformed to int)++;
}

4 Answers 4

2

If the array is a specific size and all regular integers (NSInteger in your example), why not just use a simple integer pointer? For example:

- (id)init {
  if( (self = [super init]) ) {
    // assume this is an instance variable of type NSInteger *myArray;
    myArray = (NSInteger*)calloc(arraySize, sizeof(NSInteger));

    // Do any other initialization that you need
  }
  return self;
}

- (void)myMethod {
  // Do whatever you need
  while( objects ) { myArray[whatever]++; }
}

- (void)dealloc {
  free(myArray);
  [super dealloc];
}

If your requirements call for a simple, fixed-capacity array all consisting of the same, primitive type, I think that the simple solutions are best. If the length of the array will never change (i.e., you know the length at compile time), you can use an NSInteger array as your instance variable instead of a pointer, that way you don't have to deal with allocating the memory or freeing it. Also, in that case, you will get a zero-ed out array automatically.

Sign up to request clarification or add additional context in comments.

Comments

1
NSMutableArray *a = [[NSMutableArray alloc] init];
int i;

for (i = 0; i < ...; ++i)
    [a addObject:[NSNumber numberWithInt:0]];

Comments

1

As you need to change the array you'll need to use a Mutable array rather than an immutable one.

If you need to initialise an array of 10 items to start with you could write:

NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:10];

for (NSUInteger i = 0; i < 10; i++) {
    [mutableArray insertObject:[NSNumber numberWithInt:0] atIndex:i];
}

Comments

0

You have to iterate through the whole array like this:

for ( var key in list ) {
   list[key] = // Your new object here;
}

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.