在NSDocumentDirectory中保存好吗? [英] is saving in NSDocumentDirectory okay?

查看:143
本文介绍了在NSDocumentDirectory中保存好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序正在使用 NSDocumentDirectory 将图像保存在其中,我只想询问它是否是保存图像的安全方式(最多100个)。我已经阅读了几个主题&有关它的答案的问题,虽然我不知道应该遵循哪些。有人说它可以保存在那里。有人说我不应该使用 NSDocumentDirectory 进行保存,因为它将由 iCloud 备份。那么我在哪里可以保存它,当用户退出应用程序然后再次运行应用程序,然后图像应该仍然在那里?我不太了解 tmp 目录或缓存目录。但如果它是我应该使用的2中的任何一个,我如何在我的代码中使用它们:

My app is using the NSDocumentDirectory to save images in it, I just wanna ask if its the safe way to save images(100 maximum). I have read several thread & questions with answers about it, though I dont know which to follow.Some say that its okay to save there. Some say I shouldnt use NSDocumentDirectory for saving, because it will be back-up by the iCloud. So where can I save it that when the user exit the app then run the app again, then images should still be there?. I dont know much about the tmp directory or cache directory. But if its either one of the 2 that I should use, How can I use them in my code here:

                NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,    NSUserDomainMask ,YES );
                NSString *documentsDir = [paths objectAtIndex:0];
                NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:@"Images%d.png", i]];
                ALAssetRepresentation *rep = [[info objectAtIndex: i] defaultRepresentation];
                UIImage *image = [UIImage imageWithCGImage:[rep fullResolutionImage]];
                //----resize the images
                image = [self imageByScalingAndCroppingForSize:image toSize:CGSizeMake(256,256*image.size.height/image.size.width)];

                NSData *imageData = UIImagePNGRepresentation(image);
                [imageData writeToFile:savedImagePath atomically:YES];

非常感谢您的帮助。

推荐答案

iOS定期清理 tmp 缓存目录。如果图像是一般用途,请使用相机胶卷,因为其他两个答案建议。但是,如果这些图像仅用于您的应用程序范围,您仍然可以安全地将它们存储在Documents目录中,您只需在保存后包含从iCloud备份中排除函数调用每个文件,以防止Apple拒绝你的应用程序使用太多的iCloud空间。当然有一个权衡,禁用这意味着如果用户删除应用程序或获取其他设备(等),用户将失去他们的照片,但这个警告比不在商店中获取应用程序更好。

The tmp and cache directories are periodically cleaned up by iOS. If the images are for general use, use the camera roll as the other two answers suggest. However if these images are intended just for the scope of your app, you can still safely store them in the Documents directory, you just have to include an "exclude from iCloud backup" function call to each file after saving, in order to prevent Apple rejecting your app for using too much iCloud space. Of course there's a trade-off, disabling this means the user will lose their photos anyway should they delete the app or get another device(etc), but this caveat is preferable to not getting the App on the store at all.

要禁用文件上的iCloud备份,iOS版本有两种方法> 5.0:

To disable iCloud backup on a file, there's two methods for iOS versions > 5.0:

更新!将两种方法合并为自动处理iOS版本的单一功能:

#include <sys/xattr.h> // Needed import for setting file attributes

+(BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)fileURL {

    // First ensure the file actually exists
    if (![[NSFileManager defaultManager] fileExistsAtPath:[fileURL path]]) {
        NSLog(@"File %@ doesn't exist!",[fileURL path]);
        return NO;
    }

    // Determine the iOS version to choose correct skipBackup method
    NSString *currSysVer = [[UIDevice currentDevice] systemVersion];

    if ([currSysVer isEqualToString:@"5.0.1"]) {
        const char* filePath = [[fileURL path] fileSystemRepresentation];
        const char* attrName = "com.apple.MobileBackup";
        u_int8_t attrValue = 1;
        int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
        NSLog(@"Excluded '%@' from backup",fileURL);
        return result == 0;
    }
    else if (&NSURLIsExcludedFromBackupKey) {
        NSError *error = nil;
        BOOL result = [fileURL setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:&error];
        if (result == NO) {
            NSLog(@"Error excluding '%@' from backup. Error: %@",fileURL, error);
            return NO;
        }
        else { // Succeeded
            NSLog(@"Excluded '%@' from backup",fileURL);
            return YES;
        }
    } else {
        // iOS version is below 5.0, no need to do anything
        return YES;
    }
}

如果你的应用必须支持5.0,那么不幸的是你的唯一选项是将这些照片保存在Caches目录中,这意味着它们不会被备份(这不会因此导致App Store拒绝),但只要存储监视程序决定是时候清理Caches文件夹,您就会丢失那些照片。根本不是一个理想的实现,但这就是5.0中的野兽的本质,苹果在备份排除中添加了事后补充。

If your app must support 5.0, then unfortunately your only option is to save those photos in the Caches directory, which means they won't be backed up (this not causing an App Store rejection for that reason), but whenever the storage watchdog decides it's time to clean the Caches folder, you'll lose those photos. Not an ideal implementation at all, but such is the nature of the beast in 5.0, where Apple added in Backup exclusion as an afterthought.

编辑:忘了回答'如何保存到tmp / cache目录'部分问题。如果您决定沿着这条路走下去:

Forgot to answer the 'how to save to the tmp/cache directory' part of the question. If you do decide to go down that path:


  • 保存到 tmp

NSString *tempDir = NSTemporaryDirectory();
NSString *savedImagePath = [tempDir stringByAppendingPathComponent:[NSString stringWithFormat:@"Images%d.png", i]];


(请注意,这似乎不会出现在模拟器中有任何效果,但它在设备上按预期工作)

(note that this won't appear to have any effect in the simulator, but it works as expected on device)


  • 保存到缓存

NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)lastObject];
NSString *savedImagePath = [cacheDir stringByAppendingPathComponent:[NSString stringWithFormat:@"Images%d.png", i]];


这篇关于在NSDocumentDirectory中保存好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆