Damian Van de Kauter Damian Van de Kauter - 1 year ago 169
Objective-C Question

Remove object from NSArray by index

I have a code that removes an object from an NSCollectionView, but it only removes one item. In the NSArray ("array") the value is "2 4" which returns 2, 4. But when I run the code, it only removes "2" and not "4".

The Log:

Click here for the image of the NSLOG.

The Code

NSString* LibraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPathSMSettings = [LibraryPath stringByAppendingString:stormarManagerSettingsPlistPath];
NSString *betasDef = [SMInAppCommunicationDEF stringByAppendingString:@"BETA App Id"];

NSString *indexOfApp = [Functions readDataFromPlist:plistPathSMSettings ForKey:betasDef];

if (!(indexOfApp == nil)) {
NSArray * array = [indexOfApp componentsSeparatedByString:@" "];
NSLog(@"Array: ", array);
int currentValue = 0;
for (int i = 0; i < [array count]; i++)
currentValue = [(NSNumber *)[array objectAtIndex:i] intValue];
NSLog(@"currentValue: %d", currentValue); // EXE_BAD_ACCESS
NSLog(@"x: %d", i);
[self.content removeObjectAtIndex:(currentValue)];
[self.collectionView setContent:self.content];
[self.collectionView reloadData];
NSLog(@"next: %d", currentValue); // EXE_BAD_ACCESS

else if (indexOfApp == nil) {
[self.collectionView setContent:self.content];
[self.collectionView reloadData];

Answer Source

Suppose you have a mutable array that contains [a, b, c, d], index of a is 0, b 1, c 2, d 3. But if you remove say element at index 1, then the array contains [a, c, d] and elements have now different indexes a is 0, c is 1 and d is 2...

Your array is an array of indices, so that you tried to remove element at index 2 (the third), and then after that removal element at index 4 (the fourth) but initially at index 5 (as 4>2)... Is it really what you want? [e0, e1, e2, e3, e4, e5, e6...] --> remove at index 2 --> [e0, e1, e3, e4, e5, e6...] ---> remove at index 4 --> [e0, e1, e2, e3, e4, e6...]?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download