ScanUpToCharactersFromSet stops after one cycle

I am trying to get the contents of a CSV file into an array. When I did this, before I had one record per line, and used a newline character with scanUpToCharactersFromSet:intoString:, passing newlineCharacterSetas a character set:

while ([lineScanner scanUpToCharactersFromSet:[NSCharacterSet newlineCharacterSet] 
                                   intoString:&line])

Now I am working with a file in which many entries contain newline characters. I tried to add a unique character to the end of each record (character *), but my loop only starts once. Is there something that interrupts the while loop that I don't know about? Here is the code I'm using now:

NSError *error;
NSString *data = [[NSString alloc] initWithContentsOfFile:[[self delegate] filePath] encoding:NSUTF8StringEncoding error:&error];
NSScanner *lineScanner = [NSScanner scannerWithString:data];
NSString *line = nil;

// Start parsing the CSV file
while ([lineScanner scanUpToCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:@"*"]
                    intoString:&line]) {
    NSArray *elements = [line componentsSeparatedByString:@","];
    NSLog("Name: %@", [elements objectAtIndex:1]);
}

** Edit: ** Thanks to Peter below, I found that my scanner is stuck behind the * character. I added this line in a loop:

[lineScanner scanCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:@"*"] intoString:NULL];

and now it works as it should.

+3
2

:

  • -:

    while ([lineScanner scanUpToCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:[NSCharacterSet newlineCharacterSet]] intoString:&line]) {
    

    , line. .

  • -:

    while ([lineScanner scanUpToCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:[NSCharacterSet newlineCharacterSet]] intoString:&line]) {
    

    , . , , NO. .

, . NULL , , , .

: , , . , NSScanner .

+2

, while . :

while ([theScanner isAtEnd] == NO) {
    [lineScanner scanUpToCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:@"*"] intoString:&line]
    // ...
}
0

Source: https://habr.com/ru/post/1729525/


All Articles