Step 1: Create a project based on a single view and name it TextfileRead.
Step 2: Open the ViewController. h file and write it as follows:
[Cpp]
# Import <UIKit/UIKit. h>
@ Interface ViewController: UIViewController {
NSArray * contents;
}
@ Property (nonatomic, retain) NSArray * contents;
@ End
# Import <UIKit/UIKit. h>
@ Interface ViewController: UIViewController {
NSArray * contents;
}
@ Property (nonatomic, retain) NSArray * contents;
@ End
Step 3: Open the ViewController. m file and write it as follows:
[Cpp]
# Import "ViewController. h"
@ Implementation ViewController
@ Synthesize contents;
-(Void) didReceiveMemoryWarning
{
[Super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
# Pragma mark-View lifecycle
-(Void) viewDidLoad
{
[Super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSError * error;
NSString * textContents = [NSString stringWithContentsOfFile: [[NSBundle mainBundle] pathForResource: @ "book_list" ofType: @ "rtf"] encoding: NSUTF8StringEncoding error: & error];
If (textContents = nil)
{
NSLog (@ "Error reading text file. % @", [error localizedFailureReason]);
}
Contents = [textContents componentsSeparatedByString: @ ""];
NSLog (@ "Number of lines in the file: % d", [contents count]);
NSInteger idx;
NSLog (@ "% d", [contents count]);
For (idx = 0; idx <[contents count]; idx ++)
{
NSString * current = [contents objectAtIndex: idx];
NSLog (@ "% @", current );
}
}
# Import "ViewController. h"
@ Implementation ViewController
@ Synthesize contents;
-(Void) didReceiveMemoryWarning
{
[Super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
# Pragma mark-View lifecycle
-(Void) viewDidLoad
{
[Super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSError * error;
NSString * textContents = [NSString stringWithContentsOfFile: [[NSBundle mainBundle] pathForResource: @ "book_list" ofType: @ "rtf"] encoding: NSUTF8StringEncoding error: & error];
If (textContents = nil)
{
NSLog (@ "Error reading text file. % @", [error localizedFailureReason]);
}
Contents = [textContents componentsSeparatedByString: @ ""];
NSLog (@ "Number of lines in the file: % d", [contents count]);
NSInteger idx;
NSLog (@ "% d", [contents count]);
For (idx = 0; idx <[contents count]; idx ++)
{
NSString * current = [contents objectAtIndex: idx];
NSLog (@ "% @", current );
}
}
Step 4: Run. See the following figure for details:
From Evolution