【问题标题】:Can not Archive and Unarchive file to Document Folder无法存档和取消存档文件到文档文件夹
【发布时间】:2014-05-15 18:47:15
【问题描述】:

这段代码没有给出任何错误,但它没有创建“plist”文件,也没有从中读取。

我编写了一个代码,指定了文件夹的直接路径,它创建并写入文件,尽管它无法从中读取。

[NSKeyedArchiver archiveRootObject:employees toFile:@"/Users/Documents/employees.plist"];

下面的这段代码不能读写文件。

然后我逐行按照在线说明进行操作。

我复制了准确​​的 Employee.hEmployee.m 文件,也没有错误。

感谢您的帮助。

#import <Foundation/Foundation.h>

#import "Employee.h"


NSString* getPropertyListPath() {

    NSURL *documentDir = [[NSFileManager defaultManager]
                         URLForDirectory:NSDocumentationDirectory
                                inDomain:NSUserDomainMask
                       appropriateForURL:nil
                                  create:NO
                                   error:nil];

    NSURL *plist = [documentDir URLByAppendingPathComponent:@"EmployeeFile.plist"];

    return plist.path;

}



void createAndArchiveObjects (NSString *filePath) {

    NSLog(@"Creating objects manually");

    Employee *john = [[Employee alloc] init];

    [john setFirstName:@"A"];
    [john setLastName:@"J"];
    [john setEmployeeNumber:12345];
    [john setHireDate:[NSDate date]];

    NSMutableArray *employees = [[NSMutableArray alloc] init];

    [employees addObject:john];

    [NSKeyedArchiver archiveRootObject:employees toFile:filePath];

    NSLog(@"Objects created and archived");
}



void unarchiveSavedObjects(NSString *filePath) {

    NSMutableArray *employees = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

    for (Employee *e in employees) {
        NSLog(@"The unarchived, reconstituted object is %@", e);
    }
}



int main(int argc, const char * argv[])
{

    @autoreleasepool {


        NSString *path = getPropertyListPath();

        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {

            unarchiveSavedObjects(path);

        } else {

            createAndArchiveObjects(path);

        }

    }
    return 0;
}

NSLog 显示:

Creating objects manually
Objects created and archived

但是没有创建文件。

【问题讨论】:

    标签: objective-c nskeyedarchiver nskeyedunarchiver


    【解决方案1】:

    您使用的是 NSDocumentationDirectory 而不是 NSDocumentDirectory。

    使用。,

    NSURL *documentDir = [[NSFileManager defaultManager]
                              URLForDirectory:NSDocumentDirectory
                              inDomain:NSUserDomainMask
                              appropriateForURL:nil
                              create:NO
                              error:nil];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 2020-07-10
      • 1970-01-01
      相关资源
      最近更新 更多