张运涛

c++

   :: 首页 :: 联系 :: 聚合  :: 管理

常用链接

留言簿(4)

搜索

  •  

最新评论

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:

  1. On the Mac Desktop, double-click on the Finder icon (the icon with the face on it).
  2. On the left-side of the Finder window, click on Macintosh HD.
  3. On the right-side of the Finder window, click on the Developer folder.
  4. Click on the Applications folder.
  5. 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:

  1. File > New Project.
  2. On the left-side of the New Project window, select Application under iPhone OS.
  3. On the right-side of the New Project window, select Window-Based Application.
  4. Click on the Choose button.
  5. Enter FileIo for the project name.
  6. 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:

  1. Click on the Build and Go button.
  2. After a brief moment, you should see the code running in the iPhone Simulator.
  3. Observe the status bar at the top of the window, and a white window everywhere else.
  4. 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.

  1. In Xcode, in the Groups & Files window on the left-side, click on the Classes folder.
  2. You should see the following files on the right-side of the window:
    FileIoAppDelegate.h
    FileIoAppDelegate.m
    
  3. Select FileIoAppDelegate.h so that it appears in the Xcode editor window.
  4. 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
    
  5. 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.
  6. We will not use Interface Builder for this demo, so we did not add the IBOutlet to the code that we entered.
  7. Select FileIoAppDelegate.m into the Xcode editor window.
  8. 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];
    }
    
  9. Build and Go.
  10. You should see your app running, with the text "Output will go here..." displayed in the window.
  11. 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.

  1. In Xcode, in the Groups & Files window on the left-side, click on the Resources folder.
  2. You should see the following frameworks:
    - Info.plist
    - MainWindow.xib
    
  3. Control+click on the Resources folder.
  4. Select Add from the popup menu.
  5. Select New File.
  6. In the New File window, on the left-side of the window, under the category Mac OS X, click on Other.
  7. In the New File window, on the right-side of the window, click on Empty File.
  8. Click on Next.
  9. Name the file MyFile.txt.
  10. Click on Finish.
  11. Under the Resources folder, you should now have three files:
    - MainWindow.xib
    - Info.plist
    - MyFile.txt
    
  12. Click on MyFile.txt to select it into the Xcode editor.
  13. 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).

  1. In Xcode, in the Groups & Files window on the left-side, click on the Classes folder.
  2. You should see the following files:
    - FileIoAppDelegate.h
    - FileIoAppDelegate.m
    
  3. Click on FileIoAppDelegate.m to select it into the Xcode editor.
  4. 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];
    }
    
  5. Build and Go.
  6. 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).

  1. In Xcode, click on FileIoAppDelegate.m to select it into the Xcode editor.
  2. 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];
    }
    
  3. Build and Go.
  4. 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.

  1. In Xcode, click on FileIoAppDelegate.m to select it into the Xcode editor.
  2. 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];
    }
    
  3. Build and Go.
  4. 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:.

  1. In Xcode, click on FileIoAppDelegate.m to select it into the Xcode editor.
  2. 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];
    }
    
  3. Build and Go.
  4. 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.

  1. In Xcode, click on FileIoAppDelegate.m to select it into the Xcode editor.
  2. 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];
    }
    
  3. Build and Go.
  4. 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.

  1. In Xcode, click on FileIoAppDelegate.m to select it into the Xcode editor.
  2. 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];
    }
    
  3. Build and Go.
  4. When your application runs, it displays output on the iPhone screen, and also writes the output to the NewFile.txt file.
  5. 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.

posted on 2010-12-08 15:56 张运涛 阅读(1658) 评论(0)  编辑 收藏 引用 所属分类: iphone

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理