6

Whats wrong with my code.. I want it to read a text file like

Item1

Item2

Item3

Item4

Item5

and parse it into an array so each line is a separate object in thus array.

When you check the console it prints (null)

-(void)parseIntoArray{ //parse the files into seprate arrays.
    allPools = [[NSMutableArray alloc] initWithContentsOfFile:@"ALL_POOLS_NAMES"];
    NSLog(@"%@",allPools);
}

I put the txt file in my project and copied it to destination.

1 Answer 1

13

Firstly, can you verify that the file exists where you are looking and is readable? Use

[[NSFileManager defaultManager] isReadableFileAtPath:aPath];

Secondly, what is in your file. The behaviour of initWithContentsOfFile:

The array representation in the file identified by aPath must contain only property list objects (NSString, NSData, NSArray, or NSDictionary objects).

Is your file a valid plist xml file?

InResponse

You cannot use the NSArray constructor initWithContentsOfFile: to parse a regular text file.

Instead you can read the file content into memory and parse it yourself into an array. For your example you could use

//pull the content from the file into memory
NSData* data = [NSData dataWithContentsOfFile:aPath];
//convert the bytes from the file into a string
NSString* string = [[[NSString alloc] initWithBytes:[data bytes]
                                            length:[data length] 
                                          encoding:NSUTF8StringEncoding] autorelease];

//split the string around newline characters to create an array
NSString* delimiter = @"\n";
NSArray* items = [string componentsSeparatedByString:delimiter];
Sign up to request clarification or add additional context in comments.

5 Comments

Hmm i got an error.. encoding: NSUTF8StringEncoding]]; it says its missing a : before the ] are you missing a argument?
@shorty876: No, he has one too many [ characters at the beginning.
oh wow i was trying to fix it myself but i was only looking at the closing brackets... thanksss
@Jeremy: Opps, I was going to put an autorelease but forgot by the time I looked up the UTF8 constant! Thanks.
Print this is..... "[", " {", " \"name\": \"Afghanistan\",", " \"dial_code\": \"+93\",", " \"code\": \"AF\"", " },",

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.