2013-07-11 26 views
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怎麼寫元素的數組中的plist

+0

什麼,當你使用這個事? –

回答

0

如果你使用數組,然後使用:

[urArray writeToFile:pListFilePath atomically:YES]; 

如果爲了使用詞典:

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

這條線:

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

是一個問題,因爲您試圖加載完整的目錄,而不是plist文件。

所以,當你來到這條線:

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

你試圖添加值是不存在的字典。然後當你試圖保存它時,沒有什麼可以保存的。

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

希望它會幫助你...