iOS将表单数据保存到多个文件

时间:2012-03-09 23:42:13

标签: iphone ios file save overwrite

我正在开发一个包含表单的应用。填写表单并且用户点击“提交”按钮后,将使用人员姓名和当前日期/时间保存文件。每次填写并提交表单时(不幸的是)文件都会被当前文件覆盖。我的问题是,如何在不填写上一个文件的情况下每次填写不同的文件时,如何保存相同的表单?

1 个答案:

答案 0 :(得分:0)

我写了一个算法,为任何名称冲突的文件追加一个数字:

- (NSString *)getDocumentPath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent://nameOfFile];

        //Check For Duplicate Objects
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            int i = 0;
            //Duplicate Found, enter while loop to append number to it.
            while ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                //nil out string
                NSString *newString = nil;
                NSString *pathExtension = nil;
                //build string with new number
                newString = [NSString stringWithFormat:@"%@%d",[[self.itemArray objectAtIndex:self.tableView.indexPathForSelectedRow.row] stringByDeletingPathExtension],i];
                pathExtension =[[self.itemArray objectAtIndex:self.tableView.indexPathForSelectedRow.row] pathExtension];
                //query again for duplicates
                if (![[NSFileManager defaultManager] fileExistsAtPath:[[[paths objectAtIndex:0]stringByAppendingPathComponent:newString]stringByAppendingPathExtension:pathExtension]]) {
                    //success, break,write to file
                    return [[[paths objectAtIndex:0]stringByAppendingPathComponent:newString]stringByAppendingPathExtension:pathExtension];
                    break;
                }
                //nope, increment int and try again
                i++;
            }
        }
    else return path;

}