0
- (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

4

3 回答 3

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];

希望它会帮助你...

于 2013-07-11T07:03:41.827 回答
1

这一行:

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

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

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

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

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

于 2013-07-11T06:51:50.377 回答
0

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

[urArray writeToFile:pListFilePath atomically:YES];

如果为了使用字典:

[urDictionary writeToFile:(NSString *)filePath atomically:YES]; 
于 2013-07-11T06:51:15.997 回答