如何在plist中编写元素数组

时间:2013-07-11 06:46:31

标签: iphone ios

- (void)viewDidLoad
{
NSError *error;
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [path objectAtIndex:0];
NSString *path1 = [documentDirectory stringByAppendingPathComponent:@"data.plist"];
NSFileManager *filemanager = [NSFileManager defaultManager];
NSLog( @"%@" ,documentDirectory) ;
if(![filemanager fileExistsAtPath:path1])
{
    NSString *bundle = [[NSBundle mainBundle]pathForResource:@"data" ofType:@"plist"];
    [filemanager copyItemAtPath:bundle toPath:path1 error:&error];
}


NSMutableDictionary *dictMioDB = [[NSMutableDictionary alloc] initWithContentsOfFile:documentDirectory] ;

NSMutableArray *arryRandomNumber =[[NSMutableArray alloc]init];
while (arryRandomNumber.count<10) {
    NSInteger randomNumber=1+arc4random()%10;
    if (![arryRandomNumber containsObject:[NSString stringWithFormat:@"%d",randomNumber]])       {
        [arryRandomNumber addObject:[NSString stringWithFormat:@"%d",randomNumber]];
        [dictMioDB setValue: arryRandomNumber forKey:?????????];
    }
    continue;
}

[dictMioDB writeToFile:path1 atomically:YES];
NSLog(@"%@ - %@",arryRandomNumber,[arryRandomNumber objectAtIndex:2]);

//[data writeToFile: path atomically:YES];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

我是目标c的新手,我正在尝试将元素数组写入我的plist

3 个答案:

答案 0 :(得分:1)

这一行:

NSMutableDictionary *dictMioDB = [[NSMutableDictionary alloc] initWithContentsOfFile:documentDirectory] ;

是一个问题,因为您正在尝试加载完整目录,而不是plist文件。

所以,当你走到这一行时:

[dictMioDB setValue: arryRandomNumber forKey:?????????];

您正在尝试将值添加到不存在的字典中。然后当你试图保存它时,没有什么可以保存的。

答案 1 :(得分:1)

试试这个

    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:@"username.plist"];


    NSString *x = @"xxx";
    NSString *y = @"yyy";
    NSString *z = @"zzz";

    //Load the original file
    NSMutableArray *arr;
    if([[NSFileManager defaultManager] fileExistsAtPath:plistPath])   
        //File exist load
        arr = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
    else
        //File does not exist create
        arr = [[NSMutableArray alloc] init];

    //Create dictionary
    NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: x,y,z,nil] forKeys:[NSArray arrayWithObjects: @"object1",@"object2",@"object3", nil]];

    //Append to arr
    [arr removeAllObjects];
    [arr addObject:plistDict];

    //Save to file
    [arr writeToFile:plistPath atomically:YES];

希望它会帮助你......

答案 2 :(得分:0)

如果您使用数组,请使用:

[urArray writeToFile:pListFilePath atomically:YES];

如果要使用字典:

[urDictionary writeToFile:(NSString *)filePath atomically:YES];