[英]Appending Data to .plist file programmatically
我正在使用名为name.plist
。 我试图在plist中添加New Names值,但是没有一个方法可以为我工作。 我在想什么:
#import "ViewController.h"
@interface ViewController ()
{
NSMutableArray *plist_names;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *folder = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *dir = [folder objectAtIndex:0];
NSString *path = [[NSString alloc]initWithString:[dir stringByAppendingPathComponent:@"name.plist"]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if([fileManager fileExistsAtPath:path]==NO)
{
plist_names = [[NSMutableArray alloc]init];
}
else
{
plist_names = [[NSMutableArray alloc]initWithContentsOfFile:path];
}
//NSLog(@"%@",[plist_names objectAtIndex:0]); //App Crashes
NSLog(@"%@",plist_names); //Blank Console
}
@end
我无法弄清楚我错过了什么。 我正在研究Xcode6并为ios8开发。
查看的问题: 以编程方式 将 词典添加到Plist 将数据附加到PLIST - iPhone等等
您可以将文件写入应用程序包,但实际上您不应该这样做。 您将破坏代码签名,您的应用将不再启动。 您应该使用已建立的约定,例如写入应用程序的“库”或“文档”文件夹。 请看这个SO:如何从文档目录ios获取文件名的文件路径
最后我做到了::
首先打开AppDelegate.m,然后在DidFinishLoading部分中编写以下代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
NSArray *folder = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *dir = [folder objectAtIndex:0];
NSString *path =[dir stringByAppendingPathComponent:@"name.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if([fileManager fileExistsAtPath:path]==NO)
{
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"name" ofType:@"plist"];
[fileManager copyItemAtPath:bundlePath toPath:path error:nil];
}
return YES;
}
现在ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *folder = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *dir = [folder objectAtIndex:0];
NSString *path = [dir stringByAppendingPathComponent:@"name.plist"];
NSMutableDictionary *plist_names = [[NSMutableDictionary alloc]initWithContentsOfFile:path];
NSMutableArray *names = [plist_names objectForKey:@"Names"];
NSLog(@"%@",[names objectAtIndex:1]);
[names addObject:@"jkl"];
NSLog(@"%@",[names objectAtIndex:2]);
[ plist_names setObject:names forKey:@"Names"];
[plist_names writeToFile:path atomically:YES];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.