writeToFile 没有写入文件
Posted
技术标签:
【中文标题】writeToFile 没有写入文件【英文标题】:writeToFile is not writing to the file 【发布时间】:2011-10-03 13:31:44 【问题描述】:嗯,我遇到了一个问题,我已经为此苦苦挣扎了几天。这里是:当尝试使用 writeToFile 写入 xml 文件(放置在我正在开发的 xcode 项目中)时,写入不起作用,我在 xml 文件中什么也看不到,尽管从 writeToFile 返回的布尔值是被评价为真!!此外,文件字节为零。所以,如果有人能帮我解决这个问题,我将不胜感激。以下是我写的部分代码:
//writing to a file
NSString *pathOfFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"xml"];
NSString *dummyString = @"Hello World!!\n";
NSFileManager *filemanager;
filemanager = [NSFileManager defaultManager];
//entering the first condition so I assured that the file do exists
if ([filemanager fileExistsAtPath:pathOfFile] == YES)
NSLog (@"File do exist !!!");
else
NSLog (@"File not found !!!");
BOOL writingStatus = [dummyString writeToFile:path atomically:YES encoding:NSUnicodeStringEncoding error:nil];
//Not entering this condition so I am assuming that writing process is successful but when I open the file I can't find the string hello world and file size shows 0 bytes
if(!writingStatus)
NSLog(@"Error: Could not write to the file");
我也尝试过这种替代方法,但不幸的是它也不起作用。
NSString *hello_world = @"Hello World!!\n";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *directory = [paths objectAtIndex:0];
NSString *fileName = @"sample.xml";
NSString *filePath = [directory stringByAppendingPathComponent:fileName];
NSLog(@"%@",filePath);
BOOL sucess = [hello_world writeToFile:filePath atomically:YES encoding:NSASCIIStringEncoding error:nil];
if(!sucess)
NSLog(@"Could not to write to the file");
【问题讨论】:
我们在这里讨论的是 ios 还是 MacOS X?请标记您的问题以表明这一点。 【参考方案1】:在第一段代码中,我们看不到path
的定义。如果这是一个错字并且您的意思是file_path
,那么问题是file_path
指向应用程序包内的路径。你不能在你的应用程序包内写。 (不应该有任何拼写错误,因为您应该直接粘贴代码。)
在第二种情况下,很难说出问题所在。 filePath
应该在可写的文档目录中。但是,如果您遇到实际错误,诊断问题会容易得多。不要为-writeToFile:atomically:encoding:error:
中的错误参数传递nil
,而是创建一个NSError*
变量并传入其地址。如果有问题,那么,您的指针将被设置为指向描述问题的 NSError 对象。
【讨论】:
是的,我的意思是文件路径而不是第一部分代码中的路径。这是一个错字,因为我试图定义另一条路径,然后我忘记了改变它。关于第二段代码,我将添加一个错误变量来进一步诊断问题。感谢您提供的宝贵信息,它真的很有帮助。那么,没有蚂蚁的方式我们可以写入 ye App bundle 中的文件吗? @User897,不,你是mustn't write to your app bundle。即使您能找到这样做的方法,您的数据也不会在用户同步时备份,并且您会使允许应用运行的签名无效。【参考方案2】:writeToFile:
返回布尔值 YES 的事实仅仅意味着调用正在完成。
您应该将NSError**
传递给writeToFile:
并检查它,例如:
NSError *error = nil;
BOOL ok = [hello_world writeToFile:filePath atomically:YES
encoding:NSASCIIStringEncoding error:&error];
if (error)
NSLog(@"Fail: %@", [error localizedDescription]);
这应该可以让您很好地了解发生了什么问题(假设错误在调用后不为零)。
【讨论】:
【参考方案3】:-(void)test
//writing to a file
NSError *error;
NSString *pathOfFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@".xml"];//was missing '.'
NSString *dummyString = @"Hello World!!\n";
NSFileManager *filemanager;
filemanager = [NSFileManager defaultManager];
//entering the first condition so I assured that the file do exists
//the file exists in the bundle where you cannot edit it
if ([filemanager fileExistsAtPath:pathOfFile])
NSLog (@"File do exist IN Bundle MUST be copied to editable location!!!");
NSArray *locs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [[locs objectAtIndex:0]stringByAppendingString:@"dummyFile"];
NSString *file = [docsDir stringByAppendingPathComponent:@".xml"];
[filemanager copyItemAtPath:pathOfFile toPath:file error:&error];
else
NSLog (@"File not found in bundle!!!");
if (error)
NSLog(@"error somewhere");
//if youre only messing with strings you might be better off using .plist file idk
BOOL success = [dummyString writeToFile:file atomically:YES encoding:NSUnicodeStringEncoding error:nil];
//Not entering this condition so I am assuming that writing process is successful but when I open the file I can't find the string hello world and file size shows 0 bytes
if(!success)
NSLog(@"Error: Could not write to the file");
【讨论】:
【参考方案4】://I typically do something like this
//lazy instantiate a property I want such as array.
-(NSMutableArray*)array
if (!_array)
_array = [[NSMutableArray alloc]initWithContentsOfFile:self.savePath];
return _array;
//I'm using a class to access anything in the array from as a property from any other class
//without using NSUserDefaults.
//initializing the class
-(instancetype)init
self = [super init];
if (self)
//creating an instance of NSError for error handling if need be.
NSError *error;
//build an array of locations using the NSSearchPath...
NSArray *locs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//location 0 of array is Documents Directory which is where I want to create the file
NSString *docsDir = [locs objectAtIndex:0];
//my path is now just a matter of adding the file name to the docsDir
NSString *path = [docsDir stringByAppendingPathComponent:@"fileName.plist"];
//if the file is a plist I have in my bundle I need to copy it to the docsDir to edit it
//I'll do that by getting it from the bundle that xCode made for me
NSString *bunPath = [[NSBundle mainBundle]pathForResource:@"fileName" ofType:@".plist"];
//now I need a NSFileManager to handle the dirty work
NSFileManager *filemngr = [NSFileManager defaultManager];
//if the file isn't in my docsDir I can't edit so I check and if need be copy it.
if (![filemngr fileExistsAtPath:path])
[filemngr copyItemAtPath:bunPath toPath:path error:&error];
//if an error occurs I might want to do something about it or just log it as in below.
//I believe you can set error to nil above also if you have no intentions of dealing with it.
if (error)
NSLog(@"%@",[error description]);
error = nil;
//here I'm logging the paths just so you can see in the console what's going on while building or debugging.
NSLog(@"copied file from %@ to %@",bunPath,path);
//in this case I'm assigning the array at the root of my plist for easy access
_array = [[NSMutableArray alloc]initWithContentsOfFile:path];
_savePath = path;//this is in my public api as well for easy access.
return self;
【讨论】:
以上是关于writeToFile 没有写入文件的主要内容,如果未能解决你的问题,请参考以下文章