Tag Archives: zero

NSMutableArray count always returns zero

The code is as follows, rowsToUpdate is NSMutableArray *, [sites count] is greater than 0, and there is value for row index, but [rowsToUpdate count] always returns 0:

	for (int i=0; i<[sites count]; i++) {
		NSLog(@"row index: %i, %@", i, [NSString stringWithFormat:@"%i", i]);
		[rowsToUpdate addObject:[NSString stringWithFormat:@"%i", i]];
		NSLog(@"[rowsToUpdate count] = %i", [rowsToUpdate count]);
	}

There is no obvious problem with the code, and it doesn’t make sense to return 0.

After a couple of search, I found it on stackoverflow.com that I missed the initialization for “rowsToUpdate”. The fix is as follows (a couple lines of code added):

	if (rowsToUpdate == nil) {
		rowsToUpdate = [[NSMutableArray alloc] init];
	}
	else {
		[rowsToUpdate removeAllObjects];
	}

	for (int i=0; i<[sites count]; i++) {
		NSLog(@"row index: %i, %@", i, [NSString stringWithFormat:@"%i", i]);
		[rowsToUpdate addObject:[NSString stringWithFormat:@"%i", i]];
		NSLog(@"[rowsToUpdate count] = %i", [rowsToUpdate count]);
	}