Reading from a Text File - Goal C

I am trying to get to know the C lens, and my current goal is to read the list of elements in a text file and save them in an NSString array.

This is currently what I have:

NSString *filepath = [[NSBundle mainBundle] pathForResource:@"myList" ofType:@"txt"];
NSData* data = [NSData dataWithContentsOfFile:filepath];
NSString* string = [[NSString alloc] initWithBytes:[data bytes]
                                             length:[data length]
                                           encoding:NSUTF8StringEncoding];

NSString* delimiter = @"\n";
listArray = [string componentsSeparatedByString:delimiter];

I am not sure if this is important, but myList.txtis in my supporting files.

At the moment, I have only one item in my list. However, I cannot save even this 1 element to my own listArray.

I'm sure this is something stupid that I am missing, I'm just new to Objective C.

EDIT: I apologize for not mentioning this before. I do NOT accept any mistake. My array is null.

+5
source share
2 answers

, , , . , .

NSString *filepath = [[NSBundle mainBundle] pathForResource:@"myList" ofType:@"txt"];
NSError *error;
NSString *fileContents = [NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:&error];

if (error)
    NSLog(@"Error reading file: %@", error.localizedDescription);

// maybe for debugging...
NSLog(@"contents: %@", fileContents);

NSArray *listArray = [fileContents componentsSeparatedByString:@"\n"];
NSLog(@"items = %d", [listArray count]);  
+24

:

[{"Title":"20","Cost":"20","Desc":""},{"Title":"10","Cost":"10.00","Desc":""},{"Title":"5","Cost":"5.00","Desc":""}]

-(id)readFromDocumentDBFolderPath:(NSString *)fileName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:appFile])
    {
        NSError *error= NULL;
        NSData* data = [NSData dataWithContentsOfFile:appFile];
        id resultData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        if (error == NULL)
        {
            return resultData;
        }
    }
    return NULL;
}
+1

All Articles