Servin Mobile Software
How to use iPhone with File I/O Functions: A Tutorial for Software Developers
Norman McEntire
Version 1.4 Sep 1. Thank you Freedy.
Version 1.3 Aug 6. Thank you Chris B.
Version 1.2 May 1. Thank you Pierre M.
Version 1.1 January 20
Copyright © 2009 Servin Corporation. http://servin.com
Introduction
The iPhone OS, like Mac OS X,
provides both Apple specific file I/O functions,
and Unix-type file I/O functions.
For example,
you can use Apple specific functions to
find the paths related to your application.
You can also use Apple specific Object-C classes to read/write files.
An alternative is to use Unix-specific functions to read/write files.
In addition to the standard open/close/read/write,
you can do memory mapping, where the file is mapped directly
into your address space.
In this Servin Mini-Course,
you will learn how to use Apple-specific functions and class methods
to perform file I/O.
iPhone Software Skills You Will Learn
- How to use Xcode to create a Window-Based App.
- How to display text output in a UITextView control.
- How to use NSBundle to find the resource path.
- How to use NSString to read a file.
- How to use NSSearchPathForDirectoriesInDomains() to find common search paths.
Prerequisites
Startup Xcode
If Xcode is not already running, start it up:
- On the Mac Desktop, double-click on the Finder icon (the icon with the face on it).
- On the left-side of the Finder window, click on Macintosh HD.
- On the right-side of the Finder window, click on the Developer folder.
- Click on the Applications folder.
- Double-click on the Xcode icon.
At this point, you should see the Xcode menu at the top of your desktop.
Create New Xcode Project
With Xcode running, create a new Xcode project:
- File > New Project.
- On the left-side of the New Project window, select Application under iPhone OS.
- On the right-side of the New Project window, select Window-Based Application.
- Click on the Choose button.
- Enter FileIo for the project name.
- Click on Save button.
At this point, you should see Xcode open a new window that shows a number of files.
Build Default App
Go ahead and build the default application:
-
Click on the Build and Go button.
-
After a brief moment, you should see the code running in the iPhone Simulator.
-
Observe the status bar at the top of the window,
and a white window everywhere else.
-
In the iPhone Simulator, press the Home button to stop the application.
Edit FileIoAppDelegate to Add UITextView as Subview to UIWindow
In this exercise,
you will edit FileIoAppDelegate.h and
FileIoAppDelegate.m to add a UITextView
as a subview to the UIWindow.
-
In Xcode,
in the Groups & Files window on the left-side,
click on the Classes folder.
-
You should see the following files on the right-side of the window:
FileIoAppDelegate.h
FileIoAppDelegate.m
-
Select FileIoAppDelegate.h so that it appears
in the Xcode editor window.
-
Edit the code to match the following:
#import <UIKit/UIKit.h>
@interface FileIoAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
UITextView *textView;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) UITextView *textView;
@end
-
The above code adds a member variable named textView,
which is a pointer to an object of type UITextView.
Our goal is to use the UITextView control to
display the output.
-
We will not use Interface Builder for this demo,
so we did not add the IBOutlet to the code that we entered.
-
Select FileIoAppDelegate.m into the Xcode editor window.
-
Edit the code to match the following:
#import <FileIoAppDelegate.h>
@implementation FileIoAppDelegate
@synthesize window;
@synthesize textView;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Create instance of UITextView
self.textView = [[UITextView alloc]
initWithFrame:[[UIScreen mainScreen] applicationFrame]];
// Add text
self.textView.text = @"Output will go here...";
// Make non-editable
self.textView.editable = NO;
// Add as subview to window
[window addSubview:self.textView];
// Decrement our usage count
[self.textView release];
[window makeKeyAndVisible];
}
-
Build and Go.
-
You should see your app running,
with the text "Output will go here..." displayed in the window.
-
Press Home in iPhone Simulator to stop the application.
As a review,
in this exercise you added code to the FileIoAppDelegate class to
create a UITextView,
setting it so that it cannot be edited.
You also added text to the UITextView,
and then added the UITextView to the subview of the window.
Create MyFile.txt
In this exercise,
you will create a file named MyFile.txt as a sample
text file that you will later read and display in the iPhone window.
-
In Xcode,
in the Groups & Files window on the left-side,
click on the Resources folder.
-
You should see the following frameworks:
- Info.plist
- MainWindow.xib
-
Control+click on the Resources folder.
-
Select Add from the popup menu.
-
Select New File.
-
In the New File window,
on the left-side of the window,
under the category Mac OS X,
click on Other.
-
In the New File window,
on the right-side of the window,
click on Empty File.
-
Click on Next.
-
Name the file MyFile.txt.
-
Click on Finish.
-
Under the Resources folder,
you should now have three files:
- MainWindow.xib
- Info.plist
- MyFile.txt
-
Click on MyFile.txt to select it into the Xcode editor.
-
Enter the following into the file:
This is a text file.
The file will be displayed on the iPhone.
That is all for now.
As a review,
you created a text file named MyFile.txt in the Resources
directory of your project.
NSHomeDirectory()
In this exercise,
you will use the NSHomeDirectory() function to retrieve the path
to the home directory of your application:
NSString *NSHomeDirectory(void);
An important point:
the location of your home directory is different depending on whether
you are running on the iPhone Simulator or on an actual device (iPhone or iPod Touch).
-
In Xcode,
in the Groups & Files window on the left-side,
click on the Classes folder.
-
You should see the following files:
- FileIoAppDelegate.h
- FileIoAppDelegate.m
-
Click on FileIoAppDelegate.m to select it into the Xcode editor.
-
Edit the code to match the following:
#import <FileIoAppDelegate.h>
@implementation FileIoAppDelegate
@synthesize window;
@synthesize textView;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Create instance of UITextView
self.textView = [[UITextView alloc]
initWithFrame:[[UIScreen mainScreen] applicationFrame]];
NSString *homeDir = NSHomeDirectory();
// Add text
self.textView.text = homeDir;
// Make non-editable
self.textView.editable = NO;
// Add as subview to window
[window addSubview:self.textView];
// Decrement our usage count
[self.textView release];
[window makeKeyAndVisible];
}
-
Build and Go.
-
When your application runs,
you should see a path similar to the following displayed on the screen
(the value will change based on whether you are on the iPhone Simulator
or the iPhone device):
/Users/student/Library/Application Support/iPhone/Simulator/User/Applications/...
- OR (on an actual device) -
/var/mobile/Applications/...
As a review,
in this exercise you used the NSHomeDirectory() function
to find the pathname of your applications home directory.
NSTemporaryDirectory()
In this exercise,
you will use the NSTemporaryDirectory() function to retrieve the path
to the temporary directory for use by your application.
NSString *NSTemporaryDirectory(void);
An important point:
the location of your temporary directory is different depending on whether
you are running on the iPhone Simulator or on an actual device (iPhone or iPod Touch).
-
In Xcode,
click on FileIoAppDelegate.m to select it into the Xcode editor.
-
Edit the code to match the following:
#import <FileIoAppDelegate.h>
@implementation FileIoAppDelegate
@synthesize window;
@synthesize textView;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Create instance of UITextView
self.textView = [[UITextView alloc]
initWithFrame:[[UIScreen mainScreen] applicationFrame]];
// Get home directory
NSString *homeDir = NSHomeDirectory();
// Get temporary directory
NSString *tempDir = NSTemporaryDirectory();
// Format output
NSString *s =
[NSString stringWithFormat:@"homeDir:\n"
@"%@\n"
@"tempDir:\n"
@"%@\n",
homeDir,
tempDir];
// Add text
self.textView.text = s;
// Make non-editable
self.textView.editable = NO;
// Add as subview to window
[window addSubview:self.textView];
// Decrement our usage count
[self.textView release];
[window makeKeyAndVisible];
}
-
Build and Go.
-
When your application runs,
you should see output similar to the following
(the values will change based on whether you are on the iPhone Simulator
or the iPhone device):
homeDir:
/Users/student/Library/Application Support/iPhone/Simulator/User/Applications/...
tempDir:
/var/folders/7m/....
- OR (on an actual device)
/private/var/mobile/Applications/.../tmp
As a review,
in this exercise you used the NSTemporaryDirectory() function.
NSSearchPathForDirectoriesInDomains()
In this exercise,
you will use the NSSearchPathForDirectoriesInDomains() function to retrieve
various paths:
NSArray *
NSSearchPathForDirectoriesInDomains(
NSSearchPathDirectory directory, //NSDocumentDirectory or NSCachesDirectory
NSSearchpathDomainMask domainMask, //NSUserDomainMask
BOOL exppandTilde); // YES
An important point:
Although a NSArray object is returned,
you will only use the first array entry (index 0),
which will contain an NSString.
-
In Xcode,
click on FileIoAppDelegate.m to select it into the Xcode editor.
-
Edit the code to match the following:
#import <FileIoAppDelegate.h>
@implementation FileIoAppDelegate
@synthesize window;
@synthesize textView;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Create instance of UITextView
self.textView = [[UITextView alloc]
initWithFrame:[[UIScreen mainScreen] applicationFrame]];
// Get home directory
NSString *homeDir = NSHomeDirectory();
// Get temporary directory
NSString *tempDir = NSTemporaryDirectory();
// Get documents directory
NSArray *arrayPaths =
NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *docDir = [arrayPaths objectAtIndex:0];
// Format output
NSString *s =
[NSString stringWithFormat:@"homeDir:\n"
@"%@\n"
@"tempDir:\n"
@"%@\n"
@"docDir:\n"
@"%@\n",
homeDir,
tempDir,
docDir];
// Add text
self.textView.text = s;
// Make non-editable
self.textView.editable = NO;
// Add as subview to window
[window addSubview:self.textView];
// Decrement our usage count
[self.textView release];
[window makeKeyAndVisible];
}
-
Build and Go.
-
When your application runs,
you should see output similar to the following:
homeDir:
/Users/student/Library/Application Support/iPhone/Simulator/User/Applications/...
tempDir:
/var/folder/7m/....
docDir:
/Users/student/Library/Application Support/.../Documents
As a review,
in this exercise you used the NSSearchPathForDirectoriesInDomain() function.
Using NSBundle and pathForResource:ofType:
In this exercise,
you will use the NSBundle class to
report the path to the applications resources.
The applications resources are stored in the application bundle,
and the path to this bundle can be found with the method pathForRecoure:ofType:.
-
In Xcode,
click on FileIoAppDelegate.m to select it into the Xcode editor.
-
Edit the code to match the following:
#import <FileIoAppDelegate.h>
@implementation FileIoAppDelegate
@synthesize window;
@synthesize textView;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Create instance of UITextView
self.textView = [[UITextView alloc]
initWithFrame:[[UIScreen mainScreen] applicationFrame]];
// Get home directory
NSString *homeDir = NSHomeDirectory();
// Get temporary directory
NSString *tempDir = NSTemporaryDirectory();
// Get documents directory
NSArray *arrayPaths =
NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *docDir = [arrayPaths objectAtIndex:0];
NSString *myFilePath = [[NSBundle mainBundle]
pathForResource:@"MyFile"
ofType:@"txt"];
// Format output
NSString *s =
[NSString stringWithFormat:@"homeDir:\n"
@"%@\n"
@"tempDir:\n"
@"%@\n"
@"docDir:\n"
@"%@\n"
@"myFilePath:\n"
@"%@\n",
homeDir,
tempDir,
docDir,
myFilePath];
// Add text
self.textView.text = s;
// Make non-editable
self.textView.editable = NO;
// Add as subview to window
[window addSubview:self.textView];
// Decrement our usage count
[self.textView release];
[window makeKeyAndVisible];
}
-
Build and Go.
-
When your application runs,
you should see output similar to the following:
homeDir:
/Users/student/Library/Application Support/iPhone/Simulator/User/Applications/...
tempDir:
/var/folder/7m/....
docDir:
/Users/student/Library/Application Support.../Documents
myFilePath:
/Users/student/Library/Application Support/.../FileIo.App/MyFile.txt
As a review,
in this exercise you used the NSBundle class to determine the path
to the MyFile.txt, which is stored as part of the resource bundle.
Using NSString and stringWithContentsOfFile:encoding:error:
In this exercise,
you will use the NSString class to
read the MyText.txt file.
-
In Xcode,
click on FileIoAppDelegate.m to select it into the Xcode editor.
-
Edit the code to match the following:
#import <FileIoAppDelegate.h>
@implementation FileIoAppDelegate
@synthesize window;
@synthesize textView;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Create instance of UITextView
self.textView = [[UITextView alloc]
initWithFrame:[[UIScreen mainScreen] applicationFrame]];
// Get home directory
NSString *homeDir = NSHomeDirectory();
// Get temporary directory
NSString *tempDir = NSTemporaryDirectory();
// Get documents directory
NSArray *arrayPaths =
NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString docDir = [arrayPaths objectAtIndex:0];
NSString *myFilePath = [[NSBundle mainBundle]
pathForResource:@"MyFile"
ofType:@"txt"];
NSString *myFileContents = [NSString stringWithContentsOfFile:myFilePath
encoding:NSUTF8StringEncoding
error:nil];
// Format output
NSString *s =
[NSString stringWithFormat:@"homeDir:\n"
@"%@\n"
@"tempDir:\n"
@"%@\n"
@"docDir:\n"
@"%@\n"
@"myFilePath:\n"
@"%@\n"
@"Contents of file:\n"
@"%@\n",
homeDir,
tempDir,
docDir,
myFilePath,
myFileContents];
// Add text
self.textView.text = s;
// Make non-editable
self.textView.editable = NO;
// Add as subview to window
[window addSubview:self.textView];
// Decrement our usage count
[self.textView release];
[window makeKeyAndVisible];
}
-
Build and Go.
-
When your application runs,
you should see output similar to the following:
homeDir:
/Users/student/Library/Application Support/iPhone/Simulator/User/Applications/...
tempDir:
/var/folder/7m/....
docDir:
/Users/student/Library/Application Support/.../Documents
myFilePath:
/Users/student/Library/Application Support/.../FileIo.App/MyFile.txt
Contents of file:
This is a text file.
This file will be displayed on the iPhone.
That is all for now.
As a review,
in this exercise you used the NSString class to
read the contents of MyFile.txt.
Using NSString and writeFileTo:atomically:encoding:
In this exercise,
you will use the NSString class to
write a new file named NewText.txt.
-
In Xcode,
click on FileIoAppDelegate.m to select it into the Xcode editor.
-
Edit the code to match the following:
#import <FileIoAppDelegate.h>
@implementation FileIoAppDelegate
@synthesize window;
@synthesize textView;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Create instance of UITextView
self.textView = [[UITextView alloc]
initWithFrame:[[UIScreen mainScreen] applicationFrame]];
// Get home directory
NSString *homeDir = NSHomeDirectory();
// Get temporary directory
NSString *tempDir = NSTemporaryDirectory();
// Get documents directory
NSArray *arrayPaths =
NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString docDir = [arrayPaths objectAtIndex:0];
NSString *myFilePath = [[NSBundle mainBundle]
pathForResource:@"MyFile"
ofType:@"txt"];
NSString *myFileContents = [NSString stringWithContentsOfFile:myFilePath
encoding:NSUTF8StringEncoding
error:nil];
// Format output
NSString *s =
[NSString stringWithFormat:@"homeDir:\n"
@"%@\n"
@"tempDir:\n"
@"%@\n"
@"docDir:\n"
@"%@\n"
@"myFilePath:\n"
@"%@\n"
@"Contents of file:\n"
@"%@\n",
homeDir,
tempDir,
docDir,
myFilePath,
myFileContents];
// Create pathname to Documents directory
NSString *newFilePath = [docDir stringByAppendingString:@"/NewFile.txt"];
// Write string to file
[s writeToFile:newFilePath
atomically:YES
encoding:NSUTF8StringEncoding
error:nil];
// Add text
self.textView.text = s;
// Make non-editable
self.textView.editable = NO;
// Add as subview to window
[window addSubview:self.textView];
// Decrement our usage count
[self.textView release];
[window makeKeyAndVisible];
}
-
Build and Go.
-
When your application runs,
it displays output on the iPhone screen,
and also writes the output to the NewFile.txt file.
-
While the iPhone Simulator is still running,
open up a terminal window,
and cat (concatenate) out the contents
of the file:
$ cat /Users/student/Library/Application Support/.../Documents/NewFile.txt
...
As a review,
in this exercise you used the NSString class to
write the contents of a NSString MyFile.txt.
Skills Review
- Xcode
- Window-Based Application
- UITextView
- NSHomeDirectory()
- NSTemporaryDirectory()
- NSSearchPathForDirectoriesInDomains()
- NSBundle
- mainBundle
- pathForResource:ofType:
- NSString
- stringWithContentsOfFile:encoding:error:
- writeToFile:atomically:encoding:error:
How To Contact Author
Feel free to contact the author
for any of the following:
- You have a question or comment about this mini-course.
- You need to hire Servin to help with your software development project.
- You need to hire Servin to give an on-site training course for your software development team.
Updated 2009 Sep 1
Content viewable on all web browsers, including smart mobile phone devices.
Copyright © 1995-2009 Servin Corporation. All rights reserved.