I have a small confusion. When I print my array in tableView dataSource method numberOfRowsInSection , my App crashes.
This is my code : in .h file
@interface AddColor : UIViewController<UITableViewDataSource,UITableViewDelegate>
{
UITableView *tblView;
NSArray *arrayColors;
}
@property(nonatomic,retain)NSArray *arrayColors;
@end
In .m file
@synthesize arrayColors;
- (void)viewDidLoad
{
[super viewDidLoad];
[self.navigationController setNavigationBarHidden:NO];
arrayColors = [NSArray arrayWithObjects:@"blackColor", @"darkGrayColor", @"lightGrayColor", @"whiteColor", @"grayColor", @"redColor", @"greenColor", @"blueColor", @"cyanColor", @"yellowColor", @"magentaColor", @"orangeColor", @"purpleColor", @"brownColor", nil];
tblView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 460) style:UITableViewStylePlain];
tblView.delegate=self;
tblView.dataSource=self;
[self.view addSubview:tblView];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSLog(@"%d",[arrayColors count]);//App crashes here.
return [arrayColors count];
}
My app crashes when I print [arrayColors count];
I find the solution for crash, I simply retain the array in viewDidLoad
[arrayColor retain];
and now working fine. but why my app crashes before when I print the [arrayColor count];
creates an autoreleased array – it’s unsepcified when it is released, but most likely it’s released when the
viewDidLoadmethod returns, so it’s an invalid (garbage) pointer that you access in[arrayColor count].By retaining the array, you get rid of the deallocation error, but now you’re leaking memory. The general approach of solving this the right way is to allocate and initialize the array in one of the initializer methods, like
}
and then purge it in
- deallocin order not to leak memory:}
More on the topic on Apple Developer.