XCode How to read raw data from pipe-delimited text file

Open Xcode and create a new Single View Application. For product name, use ReadPipeDelimitedTextfield and then fill out the Organization Name and Company Identifier with your customary values. Select iPhone for Devices.


I have prepared a text file to be used in this project, it can be download in this link. Download the text file and add it inside the project. 

Once the file has been added, go inside the "ViewController.m" and add the following lines of code inside the viewDidLoad:

    NSError *error;
NSString* filePath = [[NSBundle mainBundle] pathForResource:@"US States" ofType:@"txt"];
NSString *USStates = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding error:&error];
NSString *statesStripped = [USStates stringByReplacingOccurrencesOfString:@"\r" withString:@""];

NSArray *rows = [statesStripped componentsSeparatedByString:@"\n"];

NSArray *components;

for(int i = 0; i < [rows count]; i++){
if(i == 0 || [[rows objectAtIndex:i] isEqualToString:@""]){
continue;
}

components = [[rows objectAtIndex:i] componentsSeparatedByString:@"|"];

NSLog(@"State: %@ Abbr: %@", [components objectAtIndex:0], [components objectAtIndex:1]);
}

Notice how the value of "pathForResource" is equivalent to the name of the text file.

Build and Run the project, inside the console you should see the contents of the text files which are now separated.




You can download the source code of the ReadPipeDelimitedTextfield at my repository on bitbucket.

0 nhận xét:

Đăng nhận xét