使用位于文档目录中的plist

时间:2012-08-11 22:47:28

标签: iphone objective-c ios xcode

我将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:

TableViewController.h

#import <UIKit/UIKit.h>

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

@end

TableViewController.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数组?

1 个答案:

答案 0 :(得分: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:&amp; error];

这里的问题是你不检查返回代码,但盲目地假设成功。所以看看返回代码和日志错误就失败了。一旦你知道它正在工作,那么也可以在复制之后添加另一行,以便像viwDidLoad那样将文件加载到数组中(复制代码)。

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

PS:你为什么这样做:

[self performSelector:@selector(copyPlist)];

而不是:

[self copyPlist];