UITableView数据源问题。调用UITableView:cellForRowAtIndexPath:时,我的数据数组突然变空

时间:2012-03-10 11:39:09

标签: objective-c ios xcode cocoa-touch uitableview

我正在研究BNR iOS编程指南,并且在尝试解决将UITableView数据划分为多个部分的挑战时遇到了一些麻烦。我发生的事情的摘要是这个。我需要一种灵活的方法来管理tableView的各个部分,所以我构建了一个NSMutableArray来保存这些部分。数组中的每个对象都代表一个通过NSDictionary的表部分。字典有2个键,一个用于节头的字符串和一个用于保存该节的所有物的数组。我有一个小例程,它从商店类中获取allPossesions并对它们进行排序并将它们存储到适当的数组和字典中。我一直在努力重写我的代码来合并这个,我遇到了一个令人困惑的障碍。当我的应用程序在调试器中运行时,我会抛出很多NSLog来跟踪最新情况。我似乎没有遇到访问和记录我的sections数组的内容或它的大多数表视图支持方法的nsdictionaries的任何问题;但是当调用cellForRowAtIndexpath时,代码众神不再对我微笑。不知何故,当我尝试访问或注销我的财产数组时,它突然变空了。

我不能为我的生活弄清楚这一点。我现在已经在这一天打了一天,很乐意接受任何意见或帮助。下面是我的itemsViewController.h和实现。请忽略日志和注释部分。我一直试图解决这个问题并将它们留在原处,这样人们就可以告诉我,我可能需要改变一下我的方法。此外,值得注意的是,该表最初是空的,应用程序没有任何麻烦,直到我尝试添加内容。

//
//  ItemsViewController.h
//  HomePwnr

#import <Foundation/Foundation.h>
#import "ItemDetailViewController.h"

@interface ItemsViewController : UITableViewController
{
   NSMutableArray *sections; // variable to hold the number of sections
}
-(void)addNewPossession:(id)sender;
-(void)divideSections;
@end

这是实施

//
//  ItemsViewController.m
//  HomePwnr

#import "ItemsViewController.h"
#import "PossessionStore.h"
#import "Possession.h"

@implementation ItemsViewController

- (id) init
{
      NSLog(@"ItemsViewController init called");
      // Call the superclass's designated initializer
   self = [super initWithStyle:UITableViewStyleGrouped];

   if (self) {
         // create a new barItem that will send addNePossession: to itemsViewController
      UIBarButtonItem *bbi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addNewPossession:)];

         // Set this barButtonItem as the right item in the Navigation item
      [[self navigationItem] setRightBarButtonItem:bbi];

         //The Navigation item retains its buttons so release bbi
      [bbi release];

         // set the title of the navigation item
      [[self navigationItem] setTitle:@"Homepwner"];

      //[[self navigationItem] setLeftBarButtonItem:[self editButtonItem]];
   }
   sections = [[[NSMutableArray alloc] init] retain]; // added the extra retain here to make sure my sections weren't getting released pre maturely

      // set up sections here by dividing allPossessions
   [self divideSections];
   return self;
}

- (id) initWithStyle:(UITableViewStyle)style
{
   return [self init];
}

-(void)divideSections
{
   NSLog(@"divideSections called");
      // For simplicity we'll just empty out the sections array and rebuild it each time we add or modify a possesion
   [sections removeAllObjects];

   NSArray *cheapStuff = [[NSArray alloc] initWithArray:[[PossessionStore defaultStore] possesionsFromPredicate:@"valueInDollars < 50"]];
   NSArray *expensiveStuff = [[NSArray alloc] initWithArray:[[PossessionStore defaultStore] possesionsFromPredicate:@"valueInDollars >= 50"]];


   // we'll be making an NSDictionary for each section. it will hold an array of possesions for each section and it's key will serve as the sections header
   if ([cheapStuff count] > 0) { 
      NSMutableDictionary *section1 = [NSMutableDictionary dictionaryWithObject:cheapStuff forKey:@"Possessions"];
      [section1 setValue:@"Cheap Stuff" forKey:@"Header"];
      [sections addObject:section1];
         // sections now retains NSDictionary so we release it
      [section1 release];
   }
   if ([expensiveStuff count] > 0) {
      NSMutableDictionary *section2 = [NSMutableDictionary dictionaryWithObject:expensiveStuff forKey:@"Possessions"];
      [section2 setValue:@"Cheap Stuff" forKey:@"Header"];
      [sections addObject:section2];
         // sections now retains NSDictionary so we release it
      [section2 release];
   }
      //now our arrays are retained by the dictionarys so we release them
   [cheapStuff release];
   [expensiveStuff release];
   NSLog(@" End of divideSections sections holding %@", sections);

}

/*
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   ItemDetailViewController *detailViewController = [[[ItemDetailViewController alloc] init] autorelease];
      // NSArray *possessions = [[PossessionStore defaultStore] allPossessions];
      // give the detail view controller a pointer to the possesion object in row
      // get the NSDictionary located at the section index, get the dictionary's array, get the possession at row index   
   Possession *p = [[[sections objectAtIndex:[indexPath section]] objectAtIndex:0] objectAtIndex:[indexPath row]];
   [detailViewController setPossession:p];


      // push it onto the navigationControllers stack
   [[self navigationController] pushViewController:detailViewController animated:YES];


}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
      ////If the table view is asking to commit the delete command
   if (editingStyle == UITableViewCellEditingStyleDelete) {

//PossessionStore *ps = [PossessionStore defaultStore];
//   NSArray *possessions = [ps allPossessions];
//   Possession *p = [possessions objectAtIndex:[indexPath row]];

      int section = [indexPath section];
      int row = [indexPath row];
      Possession *p = [[[sections objectAtIndex:section] objectAtIndex:0] objectAtIndex:row];
      [[[PossessionStore defaultStore] allPossessions] removePossession:p];

         // remove the row from the table view with an animation
      [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
   }
}

-(void) tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
   [[PossessionStore defaultStore] movePossessionAtIndex:[sourceIndexPath row] toIndex:[destinationIndexPath row]];
}
*/


-(void)addNewPossession:(id)sender
{
   //
   NSLog(@"addNewPossession called - sections = %@", sections);
   [[PossessionStore defaultStore] createPossession];
   //NSLog(@"Possesion store now holds %@", [[PossessionStore defaultStore] allPossessions]);

      //we've added a new possession so we'll divide out the sections again
   [self divideSections];
   //NSLog(@"addNewPossession exiting - sections = %@", sections);

      //tableview returns the tablesview
   [[self tableView] reloadData];
   //NSLog(@"table view reloading data - sections = %@", sections);

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   int numSections = [[(NSArray *)[sections objectAtIndex:section] objectForKey:@"Possessions"] count];
   //NSLog(@"numberOfRowsInSection: called for section %i, returning %i.", section, numSections);
   return numSections;
}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
   NSLog(@"returning number of sections: %i", [sections count]);
      // return the count of the sections array
   return [sections count];
}

- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
   NSLog(@"tableView:titleForHeaderInSectionCalled - sections = %@", sections);
      //Configure the header titles based on the number of sections
   if ([sections count] <= 1) {
         // return simple title for only one section in table
      NSLog(@"Returning My Stuff");
      return @"My Stuff";
   } else {
      NSLog(@"The header returned is %@", [[sections objectAtIndex:section] objectForKey:@"Header"]);
         // or return the key for the dictionary entry for the current section
      return [[[sections objectAtIndex:section] objectAtIndex:section] objectForKey:@"Header"];
   }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   NSLog(@"tableView:cellForRowAtIndexPath called for section %d, Row %d", [indexPath section], [indexPath row]);
   NSLog(@"Sections = %@", sections);
   NSLog(@"The Dictionary is %@", [sections objectAtIndex:[indexPath section]]);
   //NSLog(@"thisSection array should be %@", (NSArray *)[[sections objectAtIndex:thisSection] objectForKey:@"Possessions"]);
   //NSArray *thisSectionArray = [[sections objectAtIndex:thisSection] objectForKey:@"Possessions"];
      // Check for reusable cell
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
      // If there is no cell of this type create a new one
   if (!cell) {
      cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"] autorelease];
   }

      // get the NSDictionary located at the section index, get the dictionary's array, get the possession at row index   
      //Possession *p = [thisSection objectAtIndex:[indexPath row]];
      //[[cell textLabel] setText:[p description]];
   [[cell textLabel] setText:@"cell text"];

   return cell;
}

-(void)viewWillAppear:(BOOL)animated
{
   [self divideSections];
   [super viewWillAppear:YES];
   NSLog(@"viewWillAppear called - sections = %@", sections);
}

-(void)viewDidUnload
{
   [super viewDidUnload];
   NSLog(@"viewDidUnload called - sections = %@", sections);   
}

@end

最后,这是我尝试运行应用程序的日志。小绿色指示器正好位于我尝试在应用程序崩溃后在cellForRow .......期间记录部分内容的行上。

2012-03-10 06:22:00.177 HomePwnr[44399:f803] ItemsViewController init called
2012-03-10 06:22:00.180 HomePwnr[44399:f803] divideSections called
2012-03-10 06:22:00.181 HomePwnr[44399:f803]  End of divideSections sections holding (
)
2012-03-10 06:22:00.188 HomePwnr[44399:f803] divideSections called
2012-03-10 06:22:00.189 HomePwnr[44399:f803]  End of divideSections sections holding (
)
2012-03-10 06:22:00.189 HomePwnr[44399:f803] returning number of sections: 0
2012-03-10 06:22:00.190 HomePwnr[44399:f803] returning number of sections: 0
2012-03-10 06:22:00.191 HomePwnr[44399:f803] viewWillAppear called - sections = (
)
2012-03-10 06:22:04.234 HomePwnr[44399:f803] addNewPossession called - sections = (
)
2012-03-10 06:22:04.235 HomePwnr[44399:f803] divideSections called
2012-03-10 06:22:04.237 HomePwnr[44399:f803]  End of divideSections sections holding (
        {
        Header = "Cheap Stuff";
        Possessions =         (
            "Shiny Gun (7R3K0): Worth $40, recorded on 2012-03-10 11:22:04 +0000"
        );
    }
)
2012-03-10 06:22:04.238 HomePwnr[44399:f803] returning number of sections: 1
2012-03-10 06:22:04.239 HomePwnr[44399:f803] tableView:titleForHeaderInSectionCalled - sections = (
        {
        Header = "Cheap Stuff";
        Possessions =         (
            "Shiny Gun (7R3K0): Worth $40, recorded on 2012-03-10 11:22:04 +0000"
        );
    }
)
2012-03-10 06:22:04.240 HomePwnr[44399:f803] Returning My Stuff
2012-03-10 06:22:04.241 HomePwnr[44399:f803] tableView:titleForHeaderInSectionCalled - sections = (
        {
        Header = "Cheap Stuff";
        Possessions =         (
            "Shiny Gun (7R3K0): Worth $40, recorded on 2012-03-10 11:22:04 +0000"
        );
    }
)
2012-03-10 06:22:04.241 HomePwnr[44399:f803] Returning My Stuff
2012-03-10 06:22:04.243 HomePwnr[44399:f803] tableView:cellForRowAtIndexPath called for section 0, Row 0
(lldb)

1 个答案:

答案 0 :(得分:2)

嗯,两个建议。第一种是转移到ARC(自动参考计数),因此编译器将负责所有保留/释放等。

除此之外,您的直接问题是在“divideSections”中释放section1和section2。两者都是使用方便例程dictionaryWithObject创建的,它返回一个自动发布的字典。因此,即使它被alloc例程保留并将其添加到数组部分,它的保留计数为零,因此可以随时消失。 (你可以知道这是因为惯例,只有“alloc,copy或retain”的例程才会返回保留的对象)

找到这些东西的最简单方法是让Xcode分析而不是Build。这将指出许多类似的内存问题,以及许多其他问题。

此代码参考我在下面的评论。 Section应该是NSArray属性。然后你写这样的吸气剂:

-(void) sections {
   if (!sections) {
      <<code from dividesections that ends with...>>
      self.sections = [NSArray arrayWithObjects: section1,section2,nil];
   }
   return sections;
 }

这样你知道部分总是正确的,并且不必担心何时调用divideSections。