从file.Plist读取返回Null

时间:2013-05-13 08:28:18

标签: objective-c plist nsfilemanager writetofile

为不同信息创建多个Plist路径的程序。

但只有一条路不起作用。 (我认为“writeToFile”是问题)

-(NSString *) createPath:(NSString *)withFileName
{
   NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,
YES);
   NSString *documentsDirectory = [paths objectAtIndex:0];
   NSString *path = [documentsDirectory stringByAppendingPathComponent:withFileName];
   return path;
}

路径

NSLog = /var/mobile/Applications/02CABC0A-6B5B-4097-A9D1-4336BE8230B7/Documents/MessagesDB.plist

&安培;

-(void) messagesDbFlush
{
    // save it to the file for persistency
    NSString *messagesDB_Path = [self createPath:_fileMessagesDB];
    [_messagesDB writeToFile:messagesDB_Path atomically:YES];
    NSMutableArray *ReturnsInfo = [[NSMutableArray alloc ]initWithContentsOfFile:messagesDB_Path];
    NSLog(@"ReturnsInfo is : %@", ReturnsInfo);
}

“ReturnsInfo”数组为空:/

有人请帮忙吗?

2 个答案:

答案 0 :(得分:1)

我曾经有过同样的错误 1)检查目录列表中的plist名称以匹配您的编码 2)检查项目设置,从“构建设置”>手动删除预先存在的plist。 “复制捆绑资源”,并从列表中拖放 3)选择目录列表中的plist,选中Utilities侧栏,检查Identity&输入>位置有效
4)如果您删除了应用程序的“默认”plist aka包标识符,请添加复制生成阶段,选择目标,选择pref文件夹作为绝对路径检查“仅在安装时复制”

这解决了我的返回null。

如果捆绑包标识符都失败,您可以随时通过代码将plist复制到pref文件夹:

NSString *path = [@"~/Library/Preferences/com.MyCompany.MyApp.plist" stringByExpandingTildeInPath];

BOOL PrefsExist=[[NSFileManager defaultManager] fileExistsAtPath:path];
NSString *copyPrefsPath = [@"~/Library/Preferences/com.MyCompany.MyApp.plist" stringByExpandingTildeInPath];
NSFileManager *fileManager = [NSFileManager defaultManager];

if (PrefsExist == 0)
    {
        // Copy the plist to prefs folder (one-time event)
        NSString *tessdataPath = [[NSBundle mainBundle] pathForResource:@"com.MyCompany.MyApp" ofType:@"plist"];
        [fileManager copyItemAtPath:tessdataPath toPath:path error:&error];
    } else
    {
        // Read/Write the values from plist
    }

答案 1 :(得分:0)

我已经存储了下面有5个对象的数组,它在我这边工作正常,试试吧

NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:5];
for(int i=0;i<5;i++)
    [array addObject:@"This is Demo String, You can write your own String here"];

NSString *_fileMessagesDB = @"MessagesDB.plist";
// save it to the file for persistency
NSString *messagesDB_Path = [self createPath:_fileMessagesDB];
[array writeToFile:messagesDB_Path atomically:YES];
NSMutableArray *ReturnsInfo = [[NSMutableArray alloc ]initWithContentsOfFile:messagesDB_Path];
NSLog(@"ReturnsInfo is : %@", ReturnsInfo);