0

我将字典的 plist 数组复制到设备上的文档目录中,如下所示:

AppDelegate.m:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [self performSelector:@selector(copyPlist)];
    return YES;
}

- (void)copyPlist {

    NSError *error;

    NSFileManager *fileManager=[NSFileManager defaultManager];
    NSArray *pathsArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

    NSString *doumentDirectoryPath=[pathsArray objectAtIndex:0];
    NSString *destinationPath= [doumentDirectoryPath stringByAppendingPathComponent:@"Wine.plist"];

    if ([fileManager fileExistsAtPath:destinationPath]){
        NSLog(@"database localtion %@",destinationPath);
        return;
    }

    NSString *sourcePath= [[NSBundle mainBundle] pathForResource:@"Wine" ofType:@"plist"];
    NSLog(@"source path %@",sourcePath);
    [fileManager copyItemAtPath:sourcePath toPath:destinationPath error:&error];
    }

数据库位置的日志:

/var/mobile/Applications/832E16F4-A204-457E-BFF0-6AEA27915C25/Documents/Wine.plist

然后,我尝试访问 plist 并用字典填充 sortedWines 数组以填充 TableView:

表视图控制器.h

#import <UIKit/UIKit.h>

@interface WinesViewController : UITableViewController <UIActionSheetDelegate> {
     NSMutableArray *sortedWines;
}

@end

表视图控制器.m

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Wine.plist"];
    NSLog(@"plist path %@", path);

    sortedWines = [[NSMutableArray alloc] initWithContentsOfFile:path];
    NSLog(@"objects %@", sortedWines);


    NSSortDescriptor * sortDesc = [[NSSortDescriptor alloc] initWithKey:@"Popularity" ascending:YES];
    [sortedWines sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];

    [super viewDidLoad];
}

plist 路径的日志:

/var/mobile/Applications/832E16F4-A204-457E-BFF0-6AEA27915C25/Documents/Wine.plist

和对象的日志:

(无效的)

现在如何用对象填充 sortedWines 数组?

4

1 回答 1

0

所以解决方案是你的包中的原始 plist 文件不是字典数组。

要解决此断言,请在您的 copyPlist 方法中添加几行:

NSString *sourcePath= [[NSBundle mainBundle] pathForResource:@"Wine" ofType:@"plist"];
NSLog(@"source path %@",sourcePath);
NSMutableArray *sortedWines = [[NSMutableArray alloc] initWithContentsOfFile:sourcePath];
NSLog(@"objects %@", sortedWines); // bet this is nil too

编辑

所以一旦你知道你有上面的文件,那么你需要查看/测试

    [fileManager copyItemAtPath:sourcePath toPath:destinationPath error:&error];

这里的问题是您不检查返回码,而是盲目地假设成功。因此,请查看返回代码并在其中记录错误失败。一旦你知道它正在工作,然后在复制之后添加另一行,以将文件加载到数组中,就像你的 viwDidLoad 一样(复制代码)。

如果可行,但 viewDidLoad 中缺少文件,那么唯一可能的是您或系统正在删除文档目录中的所有文件(我听说如果您的应用程序使用 iCloud,则此文件夹更改的规则。

PS:你为什么这样做:

[self performSelector:@selector(copyPlist)];

代替:

[self copyPlist];
于 2012-08-11T23:00:11.980 回答