我在程序中包含了一个plist文件,并在本地对其进行了调用
NSString *plistpath = [[NSBundle mainBundle] pathForResource:@"pli" ofType:@"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:plistpath];
NSArray *cont = [dict allValues];
我希望程序在运行时手动读取文件(而不是通过程序),从plist文件添加或删除数据,而不需要停止执行并重新运行。我可以实现这一目标吗?
请帮助
答案 0 :(得分:1)
您需要了解有关基于操作系统的dispatch_source_*
调用(gcd),以便您可以监视文件夹/文件的更改。
从这里开始: https://developer.apple.com/documentation/dispatch/1385630-dispatch_source_create
如果您想查看一个有效的示例,可以查看https://github.com/tblank555/iMonitorMyFiles
的来源PS:手动更改NSBundle对象是一种不好的做法。看来,您真正需要的是设置视图。
答案 1 :(得分:1)
这是将数据保存到.plist文件的方法
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"myData.plist"];
NSError *writeError = nil;
NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:yourDictionary format:NSPropertyListXMLFormat_v1_0 options:NSPropertyListImmutable error:&writeError];
if(plistData)
{
[plistData writeToFile:plistPath atomically:YES];
NSLog(@"Data saved sucessfully");
}
else
{
NSLog(@"Error in saveData: %@", writeError.localizedDescription);
}
从捆绑包中读取plist并从中获得根字典
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"myData.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
plistPath = [[NSBundle mainBundle] pathForResource:@"myData" ofType:@"plist"];
}
NSDictionary *resultDic = [[NSDictionary alloc] initWithContentsOfFile:plistPath];