我想在iphone中创建一个子目录(Document / MyFolder)。我可以创建子目录但不能将数据保存在子目录中。这是我的代码
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"YYYYMMDD_HHMMSS"];
NSDate *date = [[NSDate alloc] init];
NSString *currentDate = [dateFormat stringFromDate:date];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *tileImageName = [NSString stringWithFormat:@"%@%@",currentDate,@".png"];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/MyFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
}
NSData* data = UIImagePNGRepresentation(tileImage);
[data writeToFile:dataPath atomically:YES];
[dateFormat release];
[date release];
如何在此子目录中保存数据?
我还需要在用户点击按钮时删除此文件夹。如何删除此子目录(在本例中为MyFolder)?
感谢。
答案 0 :(得分:1)
您的dataPath
不包含tileImageName
。您应该定义tileImagePath
以包含tileImageName
。应该是,
NSString * tileImageName = [NSString stringWithFormat:@"%@%@",currentDate,@".png"];
NSString * dataPath = [documentsDirectory stringByAppendingPathComponent:@"MyFolder"];
NSString * tileImagePath = [dataPath stringByAppendingPathComponent:tileImageName];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
}
NSData * data = UIImagePNGRepresentation(tileImage);
[data writeToFile:tileImagePath atomically:YES];
因此,您的dataPath
与../Documents/MyFolder
类似,而不是../Documents/MyFolder/20110622_011700.png
。