obj-c将字符串写入文件无效

时间:2012-11-06 09:52:57

标签: ios nsstring writetofile

我有以下尝试将字符串写入桌面上的文件,但我收到错误。

我写的代码是:

id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];

// Get array with first index being path to desktop
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES);

// Get the first element
NSString *desktopPath = [paths objectAtIndex:0];

// Append words.txt to path
NSString *theFilePath = [desktopPath stringByAppendingPathComponent:@"glutenFreeJson.txt"];

NSError *error = nil;
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"%@\n\n", jsonString);
NSLog(@"%@\n\n", theFilePath);
[jsonString writeToFile:theFilePath atomically:YES encoding:NSStringEncodingConversionAllowLossy error:&error];
NSLog(@"Write returned error: %@", [error localizedDescription]);

这会打印“Write returned error: The operation couldn’t be completed. (Cocoa error 4.)

我不确定为什么。

更新:应用程序最初从服务器请求json数据,解析并显示它。但是,服务器已经很糟糕,并不总是及时响应,我只需要一次数据,所以我只想将它下载到我的计算机上的桌面文件夹中并将其移动到我的项目文件夹中。

2 个答案:

答案 0 :(得分:0)

iOS中没有DesktopDirectory,将NSDesktopDirectory更改为NSDocumentDirectory。它会工作。

或简单写

NSString *desktopPath = NSHomeDirectory();

答案 1 :(得分:0)

使用此,

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
相关问题