开发者

iPhone addObject to NSMutableArray from another ViewController Using IBAction

I am trying to addObject to a NSMutableArray once the user taps the Add to Favorites button I can get the data into a NSDictionary, but when I pass the NSDictionary to the Array the NSLog comes back with nil. Am I missing something?

-(IBAction) addtofavorites: (id)sender
{
    NSArray *key = [NSArray arrayWithObjects:@"Title", @"Description", nil];
    NSArray *objects = [NSArray arrayWithObjects:CurrentTitle, description.text, nil];
    NSDictionary *f开发者_如何学编程add = [[NSDictionary alloc] initWithObjects:objects forKeys:key];

    FavoritesViewController *fvc = [[FavoritesViewController alloc] init];
    [fvc.favorites addObject:fadd];
    [FavoritesViewController release];
}


What I would do is in your header file create an instance variable for your FavoritesViewController that you retain. Then use lazy init when the addtofavorites is pressed. Something like below

 if (!detailViewController) 
  {
    self.fvc = [[FavoritesViewController alloc] init];
  }

 [self.fvc.favorites addObject:fad];

Then just release the FavoritesViewController object in dealloc

- (void)dealloc {
  [fvc release];
  [super dealloc];
}


FavoritesViewController *fvc = [[FavoritesViewController alloc] init];
[fvc.favorites addObject:fadd];
[FavoritesViewController release];

doesn't look right. You should already have a FavoritesViewController initialized (in which can just access it and call -addObject:)...

EDIT

First, how does the current view controller (the one that has -addtofavorites: defined on it) relate to FavoritesViewController? How would the user navigate between these two view controllers?

Second, would the list of favorites persist across different runs of the app? If so, how do you plan to save/restore favorites?

Third, rather than add favorites to a view controller, you would probably do better to add them to an underlying 'model' that would be used to populate the FavoritesViewController.

Separating the 'model' from the 'view' can be very powerful, while also simplifying your code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜