Iterating Through NSIndexSet

时间:2015-05-12 22:13:08

标签: ios objective-c cocoa

If you have an NSArray object named anArray and an NSIndexSet object named anIndexSet, you can iterate forward through an index set as shown in below.

Excerpt, Apple Documents:

package test;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class WriteFile {

int lineNumber = 1;

protected void byLine(List<String> lines) throws IOException {
    // neue Datei erstellen
    PrintWriter writer = new PrintWriter("C:\\...\\test2.txt", "UTF-8");
    // für jeden String (eingelesene Zeile) in der Arraylist
    for( String line: lines) {
        // Counter für die Zeilennummern
            writer.println("*/ " + lineNumber + " /*" + " " + line);
            lineNumber++;
        }
    // Writer schließen
    writer.close(); 
    }

}

Why terminating NSRangeException in the above scenario?

1 个答案:

答案 0 :(得分:1)

我认为这个例子更好地描述了这种情况。另外,没有像你说的那样使用空数组。非常感谢rmaddy !!!

NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"K",@"G",@"G",@"E",@"R",@"G",@"E",@"G",@"G",@"M", nil];

NSIndexSet *anIndexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [mutableArray count])];

NSUInteger index = [anIndexSet lastIndex];

while (index != NSNotFound) {
    if ([[mutableArray objectAtIndex:index] isEqualToString:@"G"]) {
        [mutableArray removeObjectAtIndex:index];
    }
    index = [anIndexSet indexLessThanIndex:index];
}
NSLog(@" %@", mutableArray);