Muszę śledzić wartości całkowite w tablicy, a czasem muszę zmodyfikować wartość w tablicy.
Właśnie teraz to robię:
// Read an integer from the array
NSNumber* num = [NSNumber numberWithInteger:someInteger];
[numArray addObject:num];
Aby zaktualizować wartość:
// Update an integer in the array
NSNumber* num = [numArray lastObject]; // get old
NSInteger numInt = [numInt integerValue]; // convert
NSNumber* newNum = [NSNumber numberWithInteger:numInt + someAddition]; // create new
[numArray removeLastObject]; // remove old
[numArray addObject:newNum]; // set new
To jest bardzo złe. Tyle zaangażowanych obiektów, a wszystko dlatego, że NSNumber jest niezmienny. Teraz pomyślałem, że może muszę zejść do starego dobrego C i użyć CFMutableArrayRef? Czy mogę przechowywać tam proste wartości NSInteger bez całego tego narzutu?
Odpowiedzi:
1 dla odpowiedzi № 1Możesz użyć replaceObjectAtIndex: withObject:
[numArray replaceObjectAtIndex:[array count]-1 withObject:newNum];
To lepsze niż twoja metoda