我是iOS开发的新手,我在过去2天遇到了问题 我想在xcode4中创建,读取和写入.txt文件...请帮我作为完整的代码。 热烈接受你的回答。 感谢。
答案 0 :(得分:0)
对于每个iOS应用程序,您只能在应用程序的文档目录中写入文件。 这是一个示例代码。
//ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
@public
NSString *filePath;
NSString *fileData;
IBOutlet UITextView *textView;
}
@property (nonatomic, retain) NSString *filePath;
@property (nonatomic, retain) NSString *fileData;
@end
//ViewController.m
#import "ViewController.h"
@implementation ViewController
@synthesize filePath;
@synthesize fileData;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [[NSString alloc] initWithFormat:@"%@", [paths objectAtIndex:0]];
//define a file path
filePath = [[NSString alloc] initWithFormat:@"%@", [documentsDirectory stringByAppendingPathComponent:@"YourFile.txt"]];
//check if file is exists or not then write some data
NSFileManager *fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:filePath])
{
fileData = @"My name is maverick";
[fileData writeToFile:filePath atomically:YES encoding:NSUnicodeStringEncoding error:nil];
textView.text = fileData;
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)readFile:(id)sender
{
fileData = [[NSString alloc] initWithContentsOfFile:filePath usedEncoding:nil error:nil];
textView.text = fileData;
}
-(IBAction)writeFile:(id)sender
{
fileData = textView.text;
[fileData writeToFile:filePath atomically:YES encoding:NSUnicodeStringEncoding error:nil];
}
@end