0

我需要将包含的文件写入NSArrays我的 iPhone 应用程序的 Documents 文件夹中。下次我需要创建一个新文件,而不是覆盖以前的文件。

我试过这样,但它只写doc0doc1.

allDocsNSArray其他地方声明。

怎么了?谢谢!

 NSString *myDoc;
 NSString *temp;

  for (int i = 0; i < [allDocs count]; ++i){
    NSFileManager* fileMgr = [NSFileManager defaultManager];
    myDoc = [NSString stringWithFormat:@"doc%d.dat", i];
    NSString* currentFile = [documentsDirectory stringByAppendingPathComponent:myDoc];
    BOOL fileExists = [fileMgr fileExistsAtPath:currentFile];
    if (fileExists == NO){
        temp = [NSString stringWithFormat:@"doc%d.dat", i];
        break;
    } else {
        temp = [NSString stringWithFormat:@"doc%d.dat",i++];
        break;
    }
}

NSString *myArray = [documentsDirectory stringByAppendingPathComponent:myDoc];

NSMutableArray *myMutableArray = [[NSMutableArray alloc] initWithContentsOfFile: myArray];

if(myMutableArray == nil)

{

    myMutableArray = [[NSMutableArray alloc] initWithCapacity:10];

    myMutableArray = anotherArray; 
} 

[myMutableArray writeToFile:myArray atomically:YES];
4

2 回答 2

2

无论是否找到文件,每次都在第一次迭代时跳出 for 循环。您应该循环使用递增的值,i直到fileExists为 false。

- (BOOL) workFileExists:(NSString *)name {
    NSFileManager *fm = [NSFileManager defaultManager];
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *filename = [name stringByAppendingString:@".swrk"];

    return [fm fileExistsAtPath:[path stringByAppendingPathComponent:filename]];
}

- (NSString *)uniqueUntitledName {
    NSString *untitled = @"Untitled";
    NSString *name = untitled;
    int i = 1;
    while ([self workFileExists:name]) {
        name = [NSString stringWithFormat:@"%@%d", untitled, i];
        i++;
    }
    return name;
}
于 2012-06-07T14:55:20.907 回答
1
UIImage *imageForShare = [UIImage imageNamed:@"anyImage.jpg"];
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"New Folder"];
// New Folder is your folder name
NSError *error = nil;

 //in this method you are checking the path is exist or not for Folder Name
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
[[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];

//now checking the image name already exist or not

NSString *fileName = [stringPath stringByAppendingFormat:@"/image.jpg"];
if (![[NSFileManager defaultManager] fileExistsAtPath:fileName])
{
  NSLog(@"Path is available.");
  NSData *data = UIImageJPEGRepresentation(imageForShare, 1.0);
  [data writeToFile:fileName atomically:YES];
}
else
{
    NSLog(@"Path doesn't exist, same name of image is already exist.");
}

谢谢你!!

于 2012-06-07T15:44:49.617 回答