2012-04-29 19 views
8

Para mi nuevo proyecto. He cargado mi contenido de archivo csv como NSString. Primero, necesito dividir esto por línea nueva, luego dividir cada línea por comas. ¿Cómo puedo iterar todo esto? ¿Me podría ayudar?Cómo dividir la nueva línea de NSString en ObjectiveC

CSV contenido

"^ GSPC", 1403.36, "4/27/2012", "16:32", 3.38,1400.19,1406.64,1397.31,574422720 + "^ IXIC", 3069.20, "4/27/2012", "17:30", + 18.59,3060.34,3076.44,3043.30,0

ViewController.m

NSString* pathToFile = [[NSBundle mainBundle] pathForResource: @"quotes" ofType: @"csv"]; 
NSString *fileString = [NSString stringWithContentsOfFile:pathToFile encoding:NSUTF8StringEncoding error:nil]; 
if (!fileString) { 
    NSLog(@"Error reading file."); 
} 

NSArray *array = [fileString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]; 

for(int i=0; i<[array count]; i++){  
    // 
} 
+0

Ver [esta cuestión] (http://stackoverflow.com/questions/32021712/how-to-split-a- string-by-new-lines-in-swift) para respuestas Swift – Suragch

Respuesta

13

posible que desee ver en NSMutableArray.

// grab your file 
NSMutableArray *data = [[fileString componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]] mutableCopy]; 
for (int i = 0; i < [data count]; i++) 
{ 
    [data replaceObjectAtIndex: i 
        withObject: [[data objectAtIndex: i] componentsSeparatedByString: @","]]; 
} 

En relación con esto, Dave DeLong tiene una biblioteca adecuada para hacer frente a esta necesidad: https://github.com/davedelong/CHCSVParser

+0

Gracias pcperini. Pero, cuando configuro este [conteo de datos] en mi tabla numberOfRowsInSection, es 5, no 2. Por favor, ayúdenme – shebi

+0

@shebi revise su archivo de texto (csv) dentro de un Hex-Editor y vea si usa \ r \ n en su lugar de \ n. – Till

Cuestiones relacionadas