2010-08-25 146 views
1

我有一个小麻烦保存到一个plist文件,当我读数据我使用:将数据保存到plist文件

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return amounts.count; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    //Create Cell 
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"]; 

    //Fill cell 
    NSDictionary *budgetItem = [amounts objectAtIndex:indexPath.row]; 
    cell.textLabel.text = [budgetItem objectForKey:@"value"]; 
    cell.detailTextLabel.text = [budgetItem objectForKey:@"description"]; 

    //Return it 
    return cell; 
} 

- (void) loadData{ 

    // Load items 
    NSString *error; 
    NSPropertyListFormat format; 
    NSString *localizedPath = [[NSBundle mainBundle] pathForResource:@"savebudget" ofType:@"plist"]; 
    NSData *plistData = [NSData dataWithContentsOfFile:localizedPath]; 

    NSArray *amountData = [NSPropertyListSerialization propertyListFromData:plistData 
                 mutabilityOption:NSPropertyListImmutable 
                    format:&format 
                 errorDescription:&error]; 
    if (amountData) { 
     self.amounts = [[NSMutableArray alloc] initWithCapacity:[amountData count]]; 
     for (NSDictionary *amountsDictionary in amountData) { 
      [self.amounts addObject:amountsDictionary]; 
    } 
} 

从一个静态的plist文件:在正常工作我资源文件夹,但是当我尝试创建自己的,好像没有什么改变:

-(void) addData { 
    NSString *path = [[NSBundle mainBundle] pathForResource:@"saveBudget" ofType:@"plist"]; 
    NSMutableDictionary* plist = [[NSMutableDictionary alloc] initWithContentsOfFile:path]; 
    [plist setValue:amountTxt.text forKey:@"value"]; 
    [plist writeToFile:path atomically:YES]; 
    [plist release]; 

} 

- (IBAction)add:(id)sender { 
    [self addData]; 
    [self.delegate budgetEnterMinusViewControllerDidFinish:self]; 
} 

任何帮助多人欢迎...

回答

2

唉。可怕和混乱的代码。第一:用这个,而不是加载:

NSString* path = [[NSBundle mainBundle] pathForResource:@"savebudget" ofType:@"plist"]; 

NSDictionary* amountData = [NSDictionary dictionaryWithContentsOfFile: path error: NULL]; 
if (amountData) { 
    self.amounts = [NSMutableArray arrayWithArray: amountData]; 
} 

注意,没有保留或分配/初始化这里因为你是分配给一个固定属性。

所以,真正的问题:

你正在读一plist中说,你说包含字典的数组。但是,当你添加数据时,你试图将单个字典写回同一个plist。

另外,在您的addData方法中,您实际上并没有添加任何数据。

And ...如果您从您的应用程序包中加载初始数据,那么在更改它之后,您应该将它重新写回到您的~/Documents目录中。当然,下次您的应用程序启动时,还要从那里读取它。

+0

嗨St3fan,我该如何改变它来正确写入?找不到任何信息,只能写回单个数组/字典... – jimbo 2010-08-27 08:20:17