2010-02-02 42 views

回答

41
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory 

NSError *error; 
BOOL succeed = [myString writeToFile:[documentsDirectory stringByAppendingPathComponent:@"myfile.txt"] 
     atomically:YES encoding:NSUTF8StringEncoding error:&error]; 
if (!succeed){ 
    // Handle error here 
} 
+4

不要为'error:'参数传递'nil'。首先,它是错误的类型('nil'在概念上是'id',而'error:'参数是'NSError **',基本上是'id *');正确类型的常量是'NULL'。更重要的是,当这个声明失败时,你不想知道为什么吗? – 2010-06-17 06:29:38

+1

进度,但当消息成功时,您也不应该认为'error'是'nil'。测试消息是否返回“YES”或“NO”,并在返回“NO”时仅检查错误对象。引用:http://developer.apple.com/mac/library/documentation/cocoa/conceptual/ErrorHandlingCocoa/CreateCustomizeNSError/CreateCustomizeNSError.html#//apple_ref/doc/uid/TP40001806-CH204-SW1(第一个“重要的”侧栏 - 诚然,这是有点斜了) – 2010-06-17 08:25:21

+0

感谢您的意见 – Vladimir 2010-06-17 08:39:37

0

你可以使用NSUserDefaults的

节能:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; 
[prefs setObject:@"TextToSave" forKey:@"keyToLookupString"]; 

阅读:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; 
NSString *myString = [prefs stringForKey:@"keyToLookupString"]; 
+3

哥们,.txt文件 – RexOnRoids 2010-02-02 13:43:49

+0

同意你可以,这是一个有效的替代。不是他要求的,但如果你不知道使用这些首选项有多容易,你不会知道使用它们。 +1 – 2011-01-18 16:14:30

+1

不要忘记在将某些内容保存到NSUserDefaults后调用'[prefs synchronize]'! – 2014-10-26 10:37:27

3

事情是这样的:

NSString *homeDirectory; 
homeDirectory = NSHomeDirectory(); // Get app's home directory - you could check for a folder here too. 
BOOL isWriteable = [[NSFileManager defaultManager] isWritableFileAtPath: homeDirectory]; //Check file path is writealbe 
// You can now add a file name to your path and the create the initial empty file 

[[NSFileManager defaultManager] createFileAtPath:newFilePath contents:nil attributes:nil]; 

// Then as a you have an NSString you could simple use the writeFile: method 
NSString *yourStringOfData; 
[yourStringOfData writeToFile: newFilePath atomically: YES]; 
1

他是如何将NSString保存到Documents文件夹中的。保存其他类型的数据也可以通过这种方式实现。

- (void)saveStringToDocuments:(NSString *)stringToSave { 

NSString *documentsFolder = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; 
NSString *fileName = [NSString stringWithString:@"savedString.txt"]; 

NSString *path = [documentsFolder stringByAppendingPathComponent:fileName]; 

[[NSFileManager defaultManager] createFileAtPath:path contents:[stringToSave dataUsingEncoding:NSUTF8StringEncoding] attributes:nil]; 
} 
0

我正在使用此方法将一些base64编码图像数据保存到磁盘。在我的电脑上打开文本文件时,由于一些换行符和返回被自动添加,我一直无法读取数据。

下面的代码修复此问题:

myString = [myString stringByReplacingOccurrencesOfString:@"\n" withString:@""]; 
myString = [myString stringByReplacingOccurrencesOfString:@"\r" withString:@""]; 

// write string to disk 
相关问题