Chr*_*ina 7 iphone cocoa-touch objective-c
在我的应用程序中,我使用以下代码将图像/文件保存到应用程序的文档目录中:
-(void)saveImageDetailsToAppBundle{
NSData *imageData = UIImagePNGRepresentation(userSavedImage); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",txtImageName.text]]; //add our image to the path
NSLog(fullPath);
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the image
NSLog(@"image saved");
}
Run Code Online (Sandbox Code Playgroud)
但是,图像名称存在问题.如果文档目录中存在文件,则具有相同名称的新文件将覆盖旧文件.如何检查文件目录中是否存在文件名?
Dee*_*olu 14
使用NSFileManager的fileExistsAtPath:方法来检查它是否存在与否.
if ( ![fileManager fileExistsAtPath:filePath] ) {
/* File doesn't exist. Save the image at the path */
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil];
} else {
/* File exists at path. Resolve and save */
}
Run Code Online (Sandbox Code Playgroud)
if ([[NSFileManager defaultManager] fileExistsAtPath:myFilePath])
Run Code Online (Sandbox Code Playgroud)
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:@"file name"];
if([fileManager fileExistsAtPath:writablePath]){
// file exist
}
else{
// file doesn't exist
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5947 次 |
| 最近记录: |