以编程方式将数据附加到.plist文件

时间:2015-02-12 10:52:01

标签: ios objective-c iphone plist

我正在使用名为name.plist的pList。我试图在plist中添加New Names值,但是没有一个方法可以为我工作。 enter image description here 我在尝试什么:

#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开发。

观看的问题: Adding dictionaries to Plist programmatically Appending data to PLIST - iPhone 还有更多

2 个答案:

答案 0 :(得分:0)

您可以将文件写入应用程序包,但实际上您不应该这样做。您将破坏代码签名,您的应用将不再启动。您应该使用已建立的约定,例如写入应用程序的“库”或“文档”文件夹。请看这个SO:Get file path by file name from documents directory ios

答案 1 :(得分:0)

最后我做了::

首先打开AppDelegate.m和In 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];
}