开发者

How to save multiple files in bundle in iphone app?

Hi all i am trying to save image in the bundle which i have currently on my view,but the problem is that i can only save one image,if i want to save the another image it replaces the old.I am not getting how to save the multiple images in the bundle then. Here is my code.

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


}

Please Help me out, how to save multiple images, files e.t.c in bundle

Thanks in advance


You're not saving into a bundle, you're saving into your app's documents directory. There's no bundle aspect to it.

You're using the filename @"image.png" for every file that you save. Hence each new write overwrites the old one. In fact, you write each file twice. To save multiple files, use different file names.

It's also bad form to pass a numeric constant as the 'options:' parameter of NSData writeToFile:options:error: (or indeed, any similar case). The value '3' includes an undefined flag, so you should expect undefined behaviour and Apple can legitimately decline to approve your application. Probably you want to keep the NSAtomicWrite line and kill the one after it.

If you're just looking to find the first unused image.png filename, the simplest solution would be something like:

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];

There's one potential downside to that; all the filenames you try are in the autorelease pool. So they'll remain in memory at least until this particular method exits. If you end up trying thousands of them, that could become a problem — but it's not directly relevant to the answer.

Assuming you always add new files but never remove files then this problem is something you could better solve with a binary search.

File names searched will be image1.png, image2.png, etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜