I want to create a subdirectory (Document/MyFolder) in iphone. I can create subdirectory but can not save data in subdirectory. Here is my code
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] fi开发者_JAVA百科leExistsAtPath:dataPath]){
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
}
NSData* data = UIImagePNGRepresentation(tileImage);
[data writeToFile:dataPath atomically:YES];
[dateFormat release];
[date release];
How can save data in this subdirectory?
Also I need to delete this folder when user clicks button. How can I delete this subdirectory (in this case MyFolder)?
Thanks.
Your dataPath
doesn't include tileImageName
. You should define a tileImagePath
to include the tileImageName
. It should probably be,
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];
So your dataPath
is something like ../Documents/MyFolder
and not ../Documents/MyFolder/20110622_011700.png
as you intended.
精彩评论