代码之家  ›  专栏  ›  技术社区  ›  Sabby

如何在iphone应用程序中捆绑保存多个文件?

  •  1
  • Sabby  · 技术社区  · 15 年前

    这是我的密码。

    - (void)writeImageToDocuments:(UIImage*)image 
    {
        NSData  *png = UIImagePNGRepresentation(image); 
        NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSError *error = nil;
        [png writeToFile:[documentsDirectory stringByAppendingPathComponent:@"image.png"] options:NSAtomicWrite error:&error];
    
    
    }
    

    请帮助我,如何将多个图像、文件e.t.c打包保存

    提前谢谢

    1 回复  |  直到 15 年前
        1
  •  5
  •   Tommy    15 年前

    您没有保存到捆绑包中,而是保存到应用程序的文档目录中。它没有捆绑的方面。

    您对保存的每个文件都使用文件名@“image.png”。因此,每一个新的写操作都会覆盖旧的写操作。实际上,每个文件都写两次。要保存多个文件,请使用不同的文件名。

    将数字常量作为NSData writeToFile:options:error:(或任何类似的情况)的“options:”参数传递也是错误的。值“3”包含一个未定义的标志,因此您应该期望未定义的行为,苹果可以合法地拒绝批准您的应用程序。也许你想保留NSAtomicWrite行,然后杀死它后面的那个。

    如果您只是想查找第一个未使用的image.png文件名,最简单的解决方案是:

    int imageNumber = 0;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *pathToFile;
    
    do
    {
        // increment the image we're considering
        imageNumber++;
    
        // get the new path to the file
        pathToFile = [documentsDirectory stringByAppendingPathComponent:
                                               [NSString stringWithFormat:
                                                        @"image%d.png", imageNumber]];
    }
    while([fileManager fileExistsAtPath:pathToFile]);
    /* so, we loop for as long as we keep coming up with names that already exist */
    
    [png writeToFile:pathToFile options:NSAtomicWrite error:&error];
    

    这有一个潜在的缺点:您尝试的所有文件名都在autorelease池中。所以他们至少会保持记忆,直到这种特殊的方法退出。如果你最终尝试了成千上万个,那可能会成为一个问题,但这与答案没有直接关系。

    搜索的文件名为image1.png、image2.png等。