Application crashing upon release of UITableViewController
I have a class that retrieves data from core data and stores it into a NSMutablearray. It also has a function that returns this array.
datamanager.h:
@interface DataManager : NSObject {
NSMutableArray *feedItems;
...
}
@property (nonatomic, retain) NSMutableArray *feedItems;
...
datamanager.m:
...
-(void)loadNews{
(load data from core data and put it in self.feedItems)
....
}
-(NSMutableArray*)getAllItems{
return self.feedItems;
}
Now i Have a UIViewController with 2 UIviews (View1 and View2) as IBOutlets. When a button in View1 is clicked it fetches the data from the datamanager class sets it as a NSMutablearray for use for a UItableviewController (tableView1).
After allocating and initializing tableView1 and setting up the Nsmutablearray to populate the table, I add its view as subview to View 2. Now my problem is when I release tableview1 after this procedure I get a EXEC_BAD_ACCESS.
View1 Button IBAction code:
-(void)loadItems{
if ([[dataManager getAllNews] count] > 0) {
ItemTableViewController *tableView1 = [[ItemTableViewController alloc] initWithNibName:@"ItemTableViewController" bundle:nil];
[tableView1 setItemList:[sectionManager getAllItems]];
for (UIView *view in View2.subviews) {
[view removeFromSuperview];
}
[View2 addSubview:tableView1.view];
[tableView1 release]; // if this is not released it works properly else EXEC_BAD_ACCESS
}
}
tableView1 setItemList function:
-(void)setItemList:(NSMutableArray *)list{
self.ItemList = list; //self.ItemList is a开发者_如何学编程 NSMutableArray
}
How do I properly release tableView1? Ive tried autorelease too, still doesn't work.
If you are using UIViewController this way, you have to keep your tableView1 retained and then release it later when it is not used anymore. This could be done by placing
[tableView1.view removeFromSuperview];
[tableView1 release];
in your dealloc
.
There is a difference between the UITableView and the UITableViewController. The controller should stick around as long as the view is used, so you shouldn't release the UITableViewController (tableView1) there.
Release it in the dealloc method for example.
Also, why do you have a -(NSMutableArray*)getAllItems
method? This is an unnecessary step, as a synthesized property already generates getters and setters.
UITableViewControllers are designed to be used with UINavigationControllers and/or UITabBarControllers. They are not meant to be used the way you're doing this.
You CAN make this work, but you're really fighting the OS.
You should either switch to a UINavigationControllers setup, or just use a straight UITableView (without going through a UITableViewController).
精彩评论