- 浏览: 1147322 次
文章分类
最新评论
-
chenhailong:
嘿嘿,没事其实IT这样怎么干也不能成为富翁,就是穷打工的。说是 ...
80后IT跳槽男的故事!你的那? -
denger:
cxh116 写道好人 转帖不留名原文:http://www. ...
程序员的黄金时代 -
cxh116:
好人 转帖不留名
程序员的黄金时代 -
ruby_windy:
500多页的书,我也是这几天刚看到完.乔布斯是半个神,活的像人 ...
看完乔布斯传,说说感受
How to use iPhone with File I/O Functions: A Tutorial for Software Developers
转自:http://servin.com/iphone/iPhone-File-IO.html
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 useNSBundleto find the resource path.
- How to useNSStringto read a file.
- How to useNSSearchPathForDirectoriesInDomains()to find common search paths.
Prerequisites
- You should have already setup your iPhone software development environment. If this is not the case, then refer to theiPhone Flashlight App: Hands-On for Software Developers
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 onMacintosh HD.
- On the right-side of the Finder window, click on theDeveloperfolder.
- Click on theApplicationsfolder.
- Double-click on theXcodeicon.
At this point, you should see theXcodemenu at the top of your desktop.
Create New Xcode Project
WithXcoderunning, create a new Xcode project:
- File > New Project.
- On the left-side of the New Project window, selectApplicationunderiPhone OS.
- On the right-side of the New Project window, selectWindow-Based Application.
- Click on theChoosebutton.
- EnterFileIofor the project name.
- Click onSavebutton.
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 theBuild and Gobutton.
- After a brief moment, you should see the code running in theiPhone Simulator.
- Observe the status bar at the top of the window, and a white window everywhere else.
- In the iPhone Simulator, press theHomebutton to stop the application.
Edit FileIoAppDelegate to Add UITextView as Subview to UIWindow
In this exercise, you will editFileIoAppDelegate.handFileIoAppDelegate.mto add aUITextViewas a subview to theUIWindow.
- In Xcode, in theGroups & Fileswindow on the left-side, click on theClassesfolder.
- You should see the following files on the right-side of the window:
FileIoAppDelegate.h FileIoAppDelegate.m
- SelectFileIoAppDelegate.hso that it appears in theXcodeeditor 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 namedtextView, which is a pointer to an object of typeUITextView. Our goal is to use theUITextViewcontrol to display the output.
- We will not useInterface Builderfor this demo, so we did not add theIBOutletto the code that we entered.
- SelectFileIoAppDelegate.minto theXcodeeditor 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.
- PressHomein iPhone Simulator to stop the application.
As a review, in this exercise you added code to theFileIoAppDelegateclass to create aUITextView, 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 namedMyFile.txtas a sample text file that you will later read and display in the iPhone window.
- In Xcode, in theGroups & Fileswindow on the left-side, click on theResourcesfolder.
- You should see the following frameworks:
- Info.plist - MainWindow.xib
- Control+clickon theResourcesfolder.
- SelectAddfrom the popup menu.
- SelectNew File.
- In the New File window, on the left-side of the window, under the categoryMac OS X, click onOther.
- In the New File window, on the right-side of the window, click onEmpty File.
- Click onNext.
- Name the fileMyFile.txt.
- Click onFinish.
- Under theResourcesfolder, you should now have three files:
- MainWindow.xib - Info.plist - MyFile.txt
- Click onMyFile.txtto select it into theXcodeeditor.
- 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 namedMyFile.txtin theResourcesdirectory of your project.
NSHomeDirectory()
In this exercise, you will use theNSHomeDirectory()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 theGroups & Fileswindow on the left-side, click on theClassesfolder.
- You should see the following files:
- FileIoAppDelegate.h - FileIoAppDelegate.m
- Click onFileIoAppDelegate.mto select it into theXcodeeditor.
- 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 theNSHomeDirectory()function to find the pathname of your applications home directory.
NSTemporaryDirectory()
In this exercise, you will use theNSTemporaryDirectory()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 onFileIoAppDelegate.mto select it into theXcodeeditor.
- 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 theNSTemporaryDirectory()function.
NSSearchPathForDirectoriesInDomains()
In this exercise, you will use theNSSearchPathForDirectoriesInDomains()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 onFileIoAppDelegate.mto select it into theXcodeeditor.
- 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 theNSSearchPathForDirectoriesInDomain()function.
Using NSBundle and pathForResource:ofType:
In this exercise, you will use theNSBundleclass 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 methodpathForRecoure:ofType:.
- In Xcode, click onFileIoAppDelegate.mto select it into theXcodeeditor.
- 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 theNSBundleclass to determine the path to theMyFile.txt, which is stored as part of the resource bundle.
Using NSString and stringWithContentsOfFile:encoding:error:
In this exercise, you will use theNSStringclass to read theMyText.txtfile.
- In Xcode, click onFileIoAppDelegate.mto select it into theXcodeeditor.
- 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 theNSStringclass to read the contents ofMyFile.txt.
Using NSString and writeFileTo:atomically:encoding:
In this exercise, you will use theNSStringclass to write a new file namedNewText.txt.
- In Xcode, click onFileIoAppDelegate.mto select it into theXcodeeditor.
- 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 theNewFile.txtfile.
- While the iPhone Simulator is still running, open up a terminal window, andcat(concatenate) out the contents of the file:
$ cat /Users/student/Library/Application Support/.../Documents/NewFile.txt ...
As a review, in this exercise you used theNSStringclass to write the contents of a NSStringMyFile.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 tocontact the authorfor 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.
相关推荐
<br>Introduction <br>This tutorial will start with the very basis of File I/O (Input/Output) in C++. After that, I will look into aspects that are more advanced, showing you some tricks, and ...
2013/06/01 16:02 131,143 howto-argparse.pdf 2013/06/01 16:02 122,448 howto-cporting.pdf 2013/06/01 16:02 132,599 howto-curses.pdf 2013/06/01 16:02 129,325 howto-descriptor.pdf 2013/06/01 16:02 127,366...
Analog Circuit Design: A Tutorial Guide to Applications and Solutions by:Bob Dobkin, Jim Williams ISBN-10 书号: 0123851858 ISBN-13 书号: 9780123851857 Edition 版本: 1 出版日期: 2011-09-13 pages 页数: ...
C# Design Patterns: A Tutorial is a practical guide to writing C# programs using the most common patterns. This tutorial begins with clear and concise introductions to C#, object-oriented ...
* http://mdn.github.io/webgl-examples/tutorial/sample1/ * http://mdn.github.io/webgl-examples/tutorial/sample2/ * http://mdn.github.io/webgl-examples/tutorial/sample3/ * ...
Microphone Arrays : A Tutorial
Programming languages are just tools that we use to tell the computer what we want ...provide the programmer with a new set of tools to attack software solutions that require the tools that C provides.
针对Struts1的网页版的Struts Design and Programming A Tutorial
Input/Output Using Stream Classes<br/><br/>13.1 Common Background of I/O Streams<br/><br/>13.2 Fundamental Stream Classes and Objects<br/><br/>13.3 Standard Stream Operators << and >><br/><br/>13.4 ...
The text guides students to understand how data mining can be employed to solve real problems and recognize whether a data mining solution is a feasible alternative for a specific problem. ...
Struts2 Design and Programming: A Tutorial.pdf 是一本介绍Struts2的设计和编程思想的书,也可以作为一本手册来使用
The C++ Standard Library: A Tutorial and Reference, Second Edition, describes this library as now incorporated into the new ANSI/ISO C++ language standard (C++11). The book provides comprehensive ...
Doing Bayesian Data Analysis: A Tutorial with R, JAGS, and Stan, Second Edition provides an accessible approach for conducting Bayesian data analysis, as material is explained clearly with concrete ...
Physical Unclonable Functions and Applications: A Tutorial This paper is a tutorial on ongoing work in physical-disorder-based security,security analysis, and implementation choices.
Beginning Samsung ARTIK will help you understand which ARTIK modules to use for various applications, and how to produce code for them. This book goes beyond the information previously available on...
入门-后端教程弹簧启动-MONGO DB-REST API这些是我们需要提供的API: 方法Urls Actions POST / api / tutorials创建新Tutorial GET / api / tutorials检索所有Tutorial GET / api / tutorials /:id通过:id PUT / ...
Learning statistics with R:A tutorial for psychology students and other beginners(Version 0.5)Daniel NavarroUniversity of Adelaidedaniel.navarro@adelaide.edu.auOnline:...
Tour Scala and learn the basic syntax, constructs, and how to use the REPLTranslate Java syntax that you already know into Scala Learn what Scala offers over and above JavaBecome familiar with ...
java处理图像的API说明,可以设置读取方式,显示图像的动作等。