从plist填充的应用程序添加收藏夹

时间:2012-07-15 20:56:46

标签: iphone xcode nsdictionary nsnotificationcenter favorites

我正在使用带有一系列字典的plist来为TableView(原型单元格)中的选定单元格填充TableView和DetailView。我想在按下按钮时将选定的字典添加到“收藏夹”选项卡(另一个TableView)。到目前为止,这是我的代码:

到目前为止,在DetailViewController中的代码:

-(IBAction)FavoriteButton:(id)sender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ItemSelected"
                                                    object:selectedObject];


}
到目前为止

代码捕获FavoritesViewController中的对象:

[[NSNotificationCenter defaultCenter] addObserverForName:@"ItemSelected"
                                                  object:nil
                                                   queue:[NSOperationQueue mainQueue]
                                              usingBlock:^(NSNotification* notif) {
                                              [favoritedObjects release];
                                              favoritedObjects = [[notif object] retain];
                                              [self.tableView reloadData];
                                          }];

//And populate the TableView with the objects:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
 {
 return [favoritedObjects count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Favcell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

// Configure the cell...

NSString *cellValue = [favoritedObjects valueForKey:@"Name"];
cell.textlabel.text = cellValue;

return cell;
}

这显示了20个单元格,其值来自Key:来自DetailViewController中最后一个Object的“Name”,我按下了“添加到收藏夹”按钮。例如,如果我将“Gato Negro”添加到收藏夹,它会在20个单元格中显示“Gato Negro”。如果我然后将“Luna”添加到fav,它会在FavoritesViewController的20个单元格中用“Luna”替换“Gato Negro”。那么如何在收藏夹TableView中逐个显示它们呢?

如何在应用程序关闭时让NotificationCenter保存更改,以便下次记得收藏夹?

这似乎是某种沟通问题。

1 个答案:

答案 0 :(得分:0)

您正在使用对象selectedObject(我假设您的字典)发布通知。收到该通知后,您将使用此对象替换现有收藏夹:

favoritedObjects = [[notif object] retain];

实际上,favoritedObjects现在是单个selectedObject字典。这本词典可能有20个条目,这就是你最终得到20个单元格的原因。

您需要进行(至少)两次更改才能使代码正常工作:

  1. 将上面的行更改为添加通知对象到您的favoritedObjects数组(我假设这是NSMutableArray),而不是替换 favoritedObjects with selectedObject字典。您还需要创建一个favoritedObjects实例(当您第一次想要添加内容时按需创建,例如检查favoritedObjects == nil,如果它是nil,则创建一个新的NSMutableArray,或者在合适的位置创建它像viewDidLoad这样的地方(在某些时候你也可能会保存并加载收藏夹,所以无论如何将它的创建放到其中一个初始化方法中是个好主意,即使你还没准备好持久的最爱)。

  2. tableView:cellForRowAtIndexPath:中使用传递给您的indexPath来实际从您的favoritedObjects数组中获取正确的条目。

  3. 此外,如果没有可用于出列的单元格,则您的tableView:cellForRowAtIndexPath:缺少创建新单元格的代码。也许你刚刚在这里省略了这段代码?如果你没有,你需要添加该代码。

    使用小写字母(-(IBAction)favoriteButton:(id)sender而不是-(IBAction)FavoriteButton:(id)sender启动方法名称也是个好主意,甚至更好:-(IBAction)favoriteButtonPressed:(id)sender)因为这是每个人都期望的Objective-C方法看起来像:))