Search code examples
objective-cxcodeparsingtextnsarray

data from txt file to NSArray


What I would like to do is the following:

I'm using XCode 4.6.1, building an iOS App

I have an textfile (.txt) that contains my data. It is fetched from a server. The data it contains is like this:

username:userid:realname:clienttype:clientversion:latitude:longitude:number:anothernumber:

So data is seperated by ":" and all data is user defined.

Because there are 2 types of clients: clienttype1 and clienttype2 I've devided the .txt file into an array using

NSArray *dataClient = [datafile componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]; //to load txt file line for line in NSArray

NSIndexSet *clientindex = [data1 indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
    NSRange range = [(NSString *)obj rangeOfString:@":clienttype1:"];
    if (range.location != NSNotFound)
    {
        return YES;
    }
    return NO; // Set the index

NSArray *firstClients = [dataClient objectsAtIndexes:clientindex]; // create array with clienttype1 only

Now I have an array with only objects of clienttype1 data. As this:

username:userid:realname:clienttype1:clientversion:latitude:longitude:number:anothernumber: username:userid:realname:clienttype1:clientversion:latitude:longitude:number:anothernumber:

How can I separate the data per user (so per line, cause each line is a different user). So that I can use username, userid etc. As an example plot location by lat. and lon. on a map with username as title. I know how to plot, make annotations etc. It is just how to get to that data.

I was thinking of a way to read the firstClients array line for line to add each type of data into a different array. In the way of: userNameArray, useridArray etc. In this way I can fetch data per Array. But how to do this.

Any help is welcome!


Solution

  • Ok found my solution. If anything better pops up please advise.

    Used this:

    for (int i = 0; i < [firstClients count]; i++) {
        NSString *oneLine = [atcClients objectAtIndex:i];
    
        NSArray *oneLineSeparated = [oneLine componentsSeparatedByString:@":"]; 
    }
    

    Now I got an Array with: username, userid, realname etc.