1

Hi I have a csv file and I would like to parse the information there on an array so I can use it on a map. Heres is what I have from the parsing part:

NSString *filepath = [[NSBundle mainBundle] pathForResource:@"Geolocalizadas" ofType:@"csv"];
NSString *content =  [NSString stringWithContentsOfFile:filepath  encoding:NSUTF8StringEncoding error:nil];
NSLog(@"array: %@", content);
NSArray *arrayfarm = [content componentsSeparatedByString:@"\n"];
for (NSString *item in arrayfarm) {
    NSArray *itemArray = [item componentsSeparatedByString:@","];
    // log first item
    NSLog(@"%@",[itemArray objectAtIndex:0]);
}

I use the nslog onthe content and array and always get (null)

1
  • If "content" is null/empty then your file access is mucked up. Make use of "error" to find out what may be going wrong. Commented May 31, 2013 at 1:08

2 Answers 2

2

I see two potential problems with your program.

  1. You are passing a nil argument to the error: parameter in your stringWithContentsOfFile: line. If there's a possibility something might go wrong (and apparently there is), you should pass a real argument there so you can figure out what went wrong.

  2. You're using @"\r" to separate strings in the file. That's weird on a Mac (which I guess you're using since this question is about an Objective-C program), though I guess possible. You might want that to be @"\n". Or @"\r\n", I guess, if it's a DOS format file.

I made just a change for #2 above and ran your program with a test file and it seems to work fine - meaning your problem is likely with #1. It can't find the file, can't open it because of a permissions problem, or something along those lines.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, you can use componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet], but that has a tendency to produce blank "components" between every line. Plain old \n works better in virtually all cases I've run into.
0

You have to pass the full path of the file to NSString stringWithContentsOfFile:encoding:error:, not just a filename.

Where is this CSV file? Is it in the app bundle? The Documents folder? Create the full path based on its location.

15 Comments

the CSV file is on the supporting files I modify the code but still cant get it working
Try getting rid of the inDirectory: part of the pathForResource: call. Most likely the file is in the root of the resource bundle.
try that but still shows as null, aslo try a txt file but it couldn't find it
What does "pathForResource" return?
(Are you sure your file is in the bundle? Find the emulator storage in Finder and see if the file is there.)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.