将OS X中的文件保存在iOS文档文件夹等私有文件夹中

时间:2014-12-24 01:22:42

标签: objective-c macos osx-mavericks osx-yosemite

OS X是否在应用程序中有一个位置来保存文件,例如如何将文件保存到iOS中的文档文件夹。我有.plist文件为我的应用程序保存,但我只想在应用程序中访问它们。不想在用户文档文件夹或其他任何内容中有一个文件夹。

如果这很明显,那么主要是iOS人员会道歉。

2 个答案:

答案 0 :(得分:1)

我不确定你想要什么。

要获取一个存储文件位置的目录,您可以使用Application Support目录(~/Library/Application Support/[APP_NAME]/)。

要获取此目录的名称,请将NSApplicationSupportDirectory传递给-URLsForDirectory:inDomains:(请参阅:Managing Files and Directories)。


为防止用户阅读文件,您可以对其进行加密(请参阅:Encrypting and Hashing Data)。

答案 1 :(得分:0)

这对我有用:

-(void) setupApp {
    NSString * myAppPath = [[Configurations createApplicationDirectoryWithPathComponent:MY_APP_DIR_NAME] path];
   self.plistPath = [myAppPath stringByAppendingString:CONFIG_FILE_NAME];
   [self createNewConfigFileWithDictionary:yourDictionary];
}

-(void) createNewConfigFileWithDictionary:(NSDictionary*)dictionary {
    @try {
        NSFileManager * fileManager = [NSFileManager defaultManager];
        if (![fileManager fileExistsAtPath:self.plistPath]) {
                [dictionary writeToFile:self.plistPath atomically:YES];
        }
    } @catch (NSException *exception) {
        NSLog(@"[MyClass createNewConfigFileWithDictionary] Problem:%@ Description: %@", [exception name],[exception reason]);
    } @finally {}
}

+ (NSURL*) createApplicationDirectoryWithPathComponent:(NSString*)path {
    NSFileManager*fm = [NSFileManager defaultManager];
    NSURL*    dirPath = nil;
    // Find the application support directory in the home directory.
    NSArray* appSupportDir = [fm URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask];
    if ([appSupportDir count] > 0) {
        // Append the bundle ID to the URL for the
        // Application Support directory
        dirPath = [[appSupportDir objectAtIndex:0] URLByAppendingPathComponent:path];
        // If the directory does not exist, this method creates it.
        // This method is only available in macOS 10.7 and iOS 5.0 or later.
        NSError*    theError = nil;
        if (![fm createDirectoryAtURL:dirPath withIntermediateDirectories:YES attributes:nil error:&theError]) {
            @throw [NSException exceptionWithName:@"CreateApplicationDirectoryWithPathComponentException"
                                           reason:theError.localizedDescription
                                         userInfo:nil];
            return nil;
        }
    }
    return dirPath;
}

Source: