Object is deallocated don't know why? - objective-c

Please help me I am not able to understand why this is happening there a object _getProductType is deallocate without any reason. please take a look, I am not able to figure out what is happening , if you can help me I will be very thank full to you, Thanks in advance
//
// ProductComponentViewController.m
// TurfNutritionTool
//
// Created by Aashish Joshi on 10/14/11.
// Copyright 2011 Abacus Consultancy Services. All rights reserved.
//
#import "ProductComponentViewController.h"
#import <QuartzCore/QuartzCore.h>
#implementation ProductComponentViewController
#synthesize productTableView = _productTableView;
#synthesize productTypeSelector = _productTypeSelector;
#synthesize turftypePopover = _turftypePopover;
#synthesize gotTurftype = _gotTurftype;
#synthesize resultProduct = _resultProduct;
#synthesize productTableCellStyle = _productTableCellStyle;
#synthesize dbObject = _dbObject;
#synthesize getProductType = _getProductType;
#define Granular #"G"
#define Liquid #"L"
#define Tankmix #"T"
#define AllProduct #"A"
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// D o any additional setup after loading the view from its nib.
UIColor *_background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"main_bg.png"]];
self.view.backgroundColor = _background;
[_background release];
// init the segment button value
[productTypeSelector setSelectedSegmentIndex:0];
_getProductType = [[NSString alloc] initWithString:AllProduct];
// set table delegate
_productTableView.delegate = self;
// load the product
[self loadProductComponentValues];
// Set the table view to be rounded
[[_productTableView layer] setCornerRadius:5.0];
}
- (void)viewDidUnload
{
[self setProductTableView:nil];
[self setProductTypeSelector:nil];
_productTableView = nil;
_productTypeSelector = nil;
_turftypePopover = nil;
_gotTurftype = nil;
_resultProduct = nil;
_productTableCellStyle = nil;
_getProductType = nil;
[_getProductType release];
[_productTableView release];
[_productTypeSelector release];
[_turftypePopover release];
[_gotTurftype release];
[_resultProduct release];
[_productTableCellStyle release];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return YES;
}
- (void)dealloc {
[_getProductType release];
[_productTableView release];
[_productTypeSelector release];
[_turftypePopover release];
[_gotTurftype release];
[_resultProduct release];
[_productTableCellStyle release];
[super dealloc];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// #warning Incomplete method implementation.
// Return the number of rows in the section.
// NSLog(#"%s", __FUNCTION__);
return [self.resultProduct count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"productContentTableCellStyle" owner:self options:nil];
cell = _productTableCellStyle;
self.productTableCellStyle = nil;
}
NSDictionary * _productRow = [_dbObject getProductdetail:[self.resultProduct objectAtIndex:indexPath.row]];
// Configure the cell...
UILabel* _label = (UILabel *)[cell viewWithTag:1];
NSString* _linkcode = [_productRow objectForKey:#"linkcode"];
_label.text = _linkcode;
_label = (UILabel *)[cell viewWithTag:2];
NSString* _description = [_productRow objectForKey:#"description"];
_label.text = _description;
_label = (UILabel *)[cell viewWithTag:3];
NSString* _productcode = [_productRow objectForKey:#"productcode"];
_label.text = _productcode;
_label = (UILabel *)[cell viewWithTag:4];
NSString* _weight = [_productRow objectForKey:#"weight"];
_label.text = _weight;
_label = (UILabel *)[cell viewWithTag:6];
NSNumber* _costperBag = [[NSNumber alloc] initWithFloat:[[_dbObject getUserProductCost:[self.resultProduct objectAtIndex:indexPath.row]] floatValue]];
_label.text = [#"$ " stringByAppendingString:[_costperBag stringValue]];
[_costperBag autorelease];
_getProductType = [_productRow objectForKey:#"producttype"];
if ([_getProductType isEqualToString:#"G"]) {
_label = (UILabel *)[cell viewWithTag:10];
NSString* _weightTag = [[NSString alloc] initWithString:#"Weight in Lbs"];
_label.text = _weightTag;
[_weightTag autorelease];
_label = (UILabel *)[cell viewWithTag:11];
NSString* _SGNTag = [[NSString alloc] initWithString:#"SGN"];
_label.text = _SGNTag;
[_SGNTag autorelease];
_label = (UILabel *)[cell viewWithTag:5];
NSString* _sgn = [_productRow objectForKey:#"sgn"];
_label.text = _sgn;
} else if([_getProductType isEqualToString:#"L"]) {
_label = (UILabel *)[cell viewWithTag:10];
NSString* _weightTag = [[NSString alloc] initWithString:#"Weight in Ozs"];
_label.text = _weightTag;
[_weightTag autorelease];
_label = (UILabel *)[cell viewWithTag:11];
NSString* _SGTag = [[NSString alloc] initWithString:#"SG"];
_label.text = _SGTag;
[_SGTag autorelease];
_label = (UILabel *)[cell viewWithTag:5];
NSString* _sgn = [_productRow objectForKey:#"sg"];
_label.text = _sgn;
} else if([_getProductType isEqualToString:#"T"]) {
_label = (UILabel *)[cell viewWithTag:10];
NSString* _weightTag = [[NSString alloc] initWithString:#"Weight in Ozs"];
_label.text = _weightTag;
[_weightTag autorelease];
_label = (UILabel *)[cell viewWithTag:11];
NSString* _SGTag = [[NSString alloc] initWithString:#"SG"];
_label.text = _SGTag;
[_SGTag autorelease];
_label = (UILabel *)[cell viewWithTag:5];
NSString* _sgn = [_productRow objectForKey:#"sg "];
_label.text = _sgn;
}
return cell;
}
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIColor *_background = [[[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"toolbar_bkg.png"]] autorelease];
UIView* _customView = [[[UIView alloc]initWithFrame:CGRectMake(10.0, 0.0, 300.0, 44.0)]autorelease];
_customView.backgroundColor = _background;
return _customView;
}
- (UIView *) tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
UIColor *_background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"toolbar_bkg.png"]];
UIView* _customView = [[[UIView alloc]initWithFrame:CGRectMake(10.0, 0.0, 300.0, 44.0)]autorelease];
_customView.backgroundColor = _background;
[_background release];
return _customView ;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
if (_delegate != nil) {
NSString *_selectedTurftype = [_getTurftype objectAtIndex:indexPath.row];
[_delegate getSelectedTurftype:_selectedTurftype];
}
*/
// NSDictionary * _productRow = [_dbObject getProductdetail:[self.resultProduct objectAtIndex:indexPath.row]];
// Animate the deselection
[self.productTableView deselectRowAtIndexPath:[self.productTableView indexPathForSelectedRow] animated:YES];
CGRect _popoverRect = CGRectMake(800.0f, 380.0f, 10.0f, 10.0f);
if ([_turftypePopover isPopoverVisible]) {
[_turftypePopover dismissPopoverAnimated:YES];
}
else
{
ProductDetailViewController* _productDetailViewControllerObj = [[ProductDetailViewController alloc] init];
_turftypePopover = [[UIPopoverController alloc]
initWithContentViewController:_productDetailViewControllerObj];
_productDetailViewControllerObj.dbObject = _dbObject;
[_productDetailViewControllerObj getSelectedProductId:[self.resultProduct objectAtIndex:indexPath.row] ];
[_productDetailViewControllerObj release];
_turftypePopover.popoverContentSize = CGSizeMake(360, 500);
[_turftypePopover presentPopoverFromRect:_popoverRect inView:self.view
permittedArrowDirections:0 animated:YES];
}
[self.productTableView deselectRowAtIndexPath:[self.productTableView indexPathForSelectedRow] animated:YES];
}
#pragma mark - ProductComponentViewController lifecycle methods
- (IBAction)laodTurftype:(id)sender {
[self initAllTheProduct];
if (_getProductType == (id)[NSNull null] && _getProductType == nil) {
_getProductType = [NSString stringWithString:AllProduct];
}
if ([_turftypePopover isPopoverVisible]) {
[_turftypePopover dismissPopoverAnimated:YES];
}
else
{
TurftypePopoverViewController* _turftypeControllerObj = [[TurftypePopoverViewController alloc] init];
_turftypeControllerObj.dbObject = _dbObject;
_turftypeControllerObj.delegate = self;
_turftypePopover = [[UIPopoverController alloc]
initWithContentViewController:_turftypeControllerObj];
[_turftypeControllerObj release];
_turftypePopover.popoverContentSize = CGSizeMake(150, 225);
[_turftypePopover presentPopoverFromBarButtonItem:sender
permittedArrowDirections:UIPopoverArrowDirectionAny
animated:YES];
}
}
- (IBAction)setProductType:(id)sender {
switch (_productTypeSelector.selectedSegmentIndex) {
case 0:
_getProductType = [NSString stringWithString:AllProduct];
break;
case 1:
_getProductType = [NSString stringWithString:Granular];
break;
case 2:
_getProductType = [NSString stringWithString:Liquid];
break;
case 3:
_getProductType = [NSString stringWithString:Tankmix];
break;
}
[self loadProductComponentValues];
// Check Point
[TestFlight passCheckpoint:#"SET_PRODUCT_TYPE"];
}
// This is Delgate Method to get selceted product
-(void) getSelectedTurftype:(NSString*) getTurftype {
self.gotTurftype = getTurftype;
NSLog(#"self.gotTurftype %#", self.gotTurftype);
[self loadProductComponentValues];
if ([_turftypePopover isPopoverVisible]) {
[_turftypePopover dismissPopoverAnimated:YES];
}
}
-(void) initAllTheProduct {
_getProductType = [NSString stringWithString:AllProduct];
self.gotTurftype = nil;
// init the segment button value
[productTypeSelector setSelectedSegmentIndex:0];
[self loadProductComponentValues];
// Check Point
[TestFlight passCheckpoint:#"SET_ALL_PRODUCT"];
}
- (IBAction)setAllProduct:(id)sender {
[self initAllTheProduct];
}
// This Method use for Load Value of ProductComponent
- (NSMutableArray*) loadProductComponentValues {
[self.resultProduct removeAllObjects];
if (!_dbObject) [self loadDBAccessDatabase];
self.resultProduct = [[NSMutableArray alloc] initWithArray:[self.dbObject getRelatedProductArray:self.gotTurftype andProductType:_getProductType]];
[_productTableView reloadData];
return self.resultProduct;
}
- (NSMutableArray *) loadProductComponentValuesIfEmpty {
// NSLog(#"%s", __FUNCTION__);
[self initAllTheProduct];
if (!_dbObject) [self loadDBAccessDatabase];
if (!self.resultProduct || ![self.resultProduct count]) self.resultProduct = [[NSMutableArray alloc] initWithArray:[self.dbObject getRelatedProductArray:self.gotTurftype andProductType:_getProductType]];
// Check Point
[TestFlight passCheckpoint:#"LOAD_DATABASE"];
return self.resultProduct;
}
- (DBAccess *) loadDBAccessDatabase {
// NSLog(#"%s", __FUNCTION__);
if (!_dbObject) {
NSString * _dbFileName = #"turfnutritiontool.db";
_dbObject = [[DBAccess alloc] initWithSSDBAccessFilename:_dbFileName];
}
return _dbObject;
}
#end

Prefer using property accessors to directly accessing instance variables in methods other than init... and dealloc. For example, there are a number of places where your code is currently doing things like this:
_getProductType = [NSString stringWithString:AllProduct];
Leaving aside that getProductType is a silly name for a property (which goes double for the instance variable, not to mention that the synthesized setter method name would be setGetProductType), this code directly assigns an object to an instance variable without taking ownership of the object. Don't do this. Instead, do one of the following:
// First let's rename your property. In the .h file, modify the current declaration like so:
#property (nonatomic, copy) NSString *productType;
// In the .m file, change the #synthesize statement:
#synthesize productType = _productType;
// In cleaning up any compiler errors/warnings from references to the old names,
// modify code that directly assigns to the instance variable (other than in `dealloc`):
// So change this:
_getProductType = [NSString stringWithString:AllProduct];
// to the following:
self.productType = [NSString stringWithString:AllProduct];
// ...or better yet:
self.productType = AllProduct;
// Note that the above statement is equivalent to the following:
[self setProductType:AllProduct];
EDIT
Also as #samfisher correctly points out, don't set ivars to nil before sending them release messages in dealloc.

use:
self._getProductType = [[NSString alloc] initWithString:AllProduct];
change this sequence:
[_getProductType release];
[_productTableView release];
[_productTypeSelector release];
[_turftypePopover release];
[_gotTurftype release];
[_resultProduct release];
[_productTableCellStyle release];
_productTableView = nil;
_productTypeSelector = nil;
_turftypePopover = nil;
_gotTurftype = nil;
_resultProduct = nil;
_productTableCellStyle = nil;
_getProductType = nil;
you were leaking memory as setting pointers to nil, //memory leak
first you should release then set pointers to nil;// no leak

When _getProductType is allocated on this line
_getProductType = [[NSString alloc] initWithString:AllProduct];
it is not retained in any way.
and as soon as _getProductType goes out of scope (which is after viewDidLoad finishes) you will not be able to reference a valid object.
so every time you reference _getProductType outside of viewDidLoad it will be as if 'released'.
Your dealloc method releases it correctly so all you have to do is add a 'retain' after allocation/initialisation, thus:
_getProductType = [[[NSString alloc] initWithString:AllProduct] retain];
However, it might be a really good idea to study properties and how they work, how they can be set up to do things like retaining or copying data as and when it is initialised. Your starting point is here.

Related

Calling a method from another class doesn't return

I'm using parse.com. I'm trying to display comments but in order to get the comments I have to get the PFObject from my DetailViewController but it doesn't return the PFObject to CommentsViewController
EDIT
here is all the code. I'm new to objective c so I'm probably doing something stupid
CommentsView Controller
#import "CommentsViewController.h"
#import "DetailViewController.h"
#import "CommentsCell.h"
#interface CommentsViewController (){
NSArray *commentsArray;
id commentInstance;
}
#end
#implementation CommentsViewController
- (id)init {
if (self = [super init]) {
[self performSelector:#selector(commentsQuery)];
}
return self;
}
- (void)commentsQuery {
commentInstance = [[DetailViewController alloc] init];
PFObject *tempObj = [commentInstance placeObject];
PFQuery *query1 = [PFQuery queryWithClassName:#"activity"];
[query1 whereKey:#"type" equalTo:#"comment"];
[query1 whereKey:#"place" equalTo:[NSString stringWithFormat:#"%#", [tempObj objectId]]];
NSLog(#"%#", tempObj);
[query1 orderByDescending:#"createdAt"];
[query1 findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error){
commentsArray = [[NSArray alloc]initWithArray:objects];
NSLog(#"%lu", (unsigned long)[commentsArray count]);
}
}];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
static NSString *CellIdentifier = #"Cell";
CommentsCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[CommentsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
PFObject *placeObj = [commentInstance placeObject];
cell.username.text = #"test";
return cell;
}
#end
DetailsViewCOntroller
#import "DetailViewController.h"
#import "CommentsViewController.h"
#interface DetailViewController (){
CommentsViewController *test;
}
#end
#implementation DetailViewController
#synthesize place;
#synthesize userPhoto, message, username, checkCount, photo, scroller, commentsTableView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
test = [[CommentsViewController alloc] init];
self.commentsTableView.delegate = test;
self.commentsTableView.dataSource = test;
//Adjust the message label box height
CGSize textSize = [[place objectForKey:#"message"] sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:CGSizeMake(201, CGFLOAT_MAX) lineBreakMode: NSLineBreakByWordWrapping];
userPhoto.file = [place objectForKey:#"thumbnail"];
[userPhoto loadInBackground];
username.text = [place objectForKey:#"username"];
message.text = [place objectForKey:#"message"];
checkCount.text = [NSString stringWithFormat:#"%#", [place objectForKey:#"checkMarkCount"]];
[message sizeToFit];
if ([place objectForKey:#"photo"] != Nil){
photo.file = [place objectForKey:#"photo"];
[photo loadInBackground];
//[photo sizeToFit];
photo.frame = CGRectMake(6, textSize.height + 50, photo.frame.size.width, photo.frame.size.height);
float sizeOfContent = 0;
UIView *lLast = [scroller.subviews lastObject];
NSInteger wd = lLast.frame.origin.y;
NSInteger ht = lLast.frame.size.height;
NSLog(#"%#", lLast);
sizeOfContent = wd+ht;
scroller.contentSize = CGSizeMake(scroller.frame.size.width, sizeOfContent+100);
}
else{
float sizeOfContent = 0;
UIView *lLast = [scroller.subviews lastObject];
NSInteger wd = lLast.frame.origin.y;
NSInteger ht = lLast.frame.size.height;
NSLog(#"%#", lLast);
sizeOfContent = wd+ht;
scroller.contentSize = CGSizeMake(scroller.frame.size.width, sizeOfContent+100);
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)checkMarkButton:(UIButton *)sender {
}
- (PFObject *)placeObject{
return place;
}
#end
I do not see where you allocate place object. You call init and then try retrieving place. It should return nil. Here is your code:
commentInstance = [[DetailViewController alloc] init];
PFObject *tempObj = [commentInstance placeObject];
commentInstance is a new object. There is no init function defined in DetailViewController, hence commentInstance.place is nil and that is returned by placeObject method.
You define place as a property
#property ... place
That gives you a member variable _pace and two member functions, place() and setPlace(place). The object itself is not allocated for you.
Allocate place object in your init function, get rid of placeObject(), replace it with object.place call.
I got rid of all that and in my DetailViewController I added [test placeSet:place] in my viewDidLoad method. Then in CommentsViewController I did...
- (void)placeSet:(PFObject *)object{
place = object;
NSLog(#"place = %#", place);
}

how to create image in cell table view

I want create one page in way table view. its display 4 cell that different image and name for any cell. (this information get url in loop)
first : I create one class that I can meaning 2 variable.
Recipe.h
#import
#interface Recipe : NSObject
#property (nonatomic, strong) NSString *name; // name of recipe
#property (nonatomic, strong) NSString *imageFile; // image filename of recipe
#end so now in RecipeViewController (root) I write this code :
#import "RecipeViewController.h"
#import "Recipe.h"
#interface RecipeViewController ()
{
IBOutlet UIImageView *ab;
}
#end
#implementation RecipeViewController
{
NSMutableArray *recipes;
NSInteger num;
}
#synthsize ab;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title = #"Recipe Book";
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:#"Back" style:UIBarButtonItemStyleBordered target:nil
action:nil];
[[self navigationItem] setBackBarButtonItem:backButton];
NSString *numberbook = [[NSString alloc]initWithContentsOfURL:[NSURL
URLWithString:#"http://192.168.1.102/mamal/book.php?all"]];
NSInteger numbook = [numberbook integerValue];
NSMutableArray *b = [[NSMutableArray alloc]initWithCapacity:numbook];
for (int i = 1; i <= numbook; i++)
{
Recipe *si = [Recipe new];
NSLog(#"%d,%#",i,si);
NSString *c = [[NSString alloc]initWithContentsOfURL:[NSURL URLWithString:[NSString
stringWithFormat:#"http://192.168.1.102/mamal/book.php?info=1&b=%d",i]]];
NSString *a = [NSString stringWithFormat:#"http://192.168.1.102/mamal/book.php?p=1&b=%d",i];
[b addObject:a];
UIImage *myImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:a]]];
[ab setImage:myImage];
NSLog(#"%#",a);
NSLog(#"%#",c);
si.name = [NSString stringWithString:c];
si.imageFile =[]; //I so confused!!!
if(!recipes){
recipes = [NSMutableArray array];
}
[recipes addObject:si];
}
num = numbook;
// Remove table cell separator
[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
// Assign our own backgroud for the view
self.parentViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"common_bg"]];
self.tableView.backgroundColor = [UIColor clearColor];
// Add padding to the top of the table view
UIEdgeInsets inset = UIEdgeInsetsMake(5, 0, 0, 0);
self.tableView.contentInset = inset;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return recipes.count;
}
- (UIImage *)cellBackgroundForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger rowCount = [self tableView:[self tableView] numberOfRowsInSection:0];
NSInteger rowIndex = indexPath.row;
UIImage *background = nil;
if (rowIndex == 0) {
background = [UIImage imageNamed:#"cell_top.png"];
} else if (rowIndex == rowCount - 1) {
background = [UIImage imageNamed:#"cell_bottom.png"];
} else {
background = [UIImage imageNamed:#"cell_middle.png"];
}
return background;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
// Display recipe in the table cell
Recipe *recipe = [recipes objectAtIndex:indexPath.row];
UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
recipeImageView.image = [UIImage imageNamed:recipe.imageFile];
UILabel *recipeNameLabel = (UILabel *)[cell viewWithTag:101];
recipeNameLabel.text = recipe.name;
UILabel *recipeDetailLabel = (UILabel *)[cell viewWithTag:102];
recipeDetailLabel.text = recipe.detail;
// Assign our own background image for the cell
UIImage *background = [self cellBackgroundForRowAtIndexPath:indexPath];
UIImageView *cellBackgroundView = [[UIImageView alloc] initWithImage:background];
cellBackgroundView.image = background;
cell.backgroundView = cellBackgroundView;
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
#end
I so confused and get this error :
"connection cannot have a prototype object as its destination"
also I don't know one way for display image in cell!!!
cell.imageView.image = yourImage
Try this
cell.yourImage.image = [UIImage imageNamed:#"imageName"];

UInavigationbar and super dealloc causing app crash

I am having a application crash when i use back button in UINavigation child and child [supper dealloc] called application get crash. I tried but i am not able to find any error. Instrument saying below issue but i am not getting the point here
# Address Category Event Type RefCt Timestamp Size Responsible Library Responsible Caller
0 0x9e8c8c0 CALayer Malloc 1 00:05.082.180 48 UIKit -[UIView _createLayerWithFrame:]
1 0x9e8c8c0 CALayer Zombie -1 00:18.855.037 0 QuartzCore CA::release_objects(X::List<void const*>*)
if you can help me i will be great thankfull to you.
Here is the root page code
//
// TNTScenarioViewController.m
// TurfNutritionTool
//
// Created by Aashish Joshi on 10/20/11.
// Copyright 2011 Abacus Consultancy Services. All rights reserved.
//
#import "TNTScenarioViewController.h"
#import "ScenarioDetailViewController.h"
#import <QuartzCore/QuartzCore.h>
#implementation TNTScenarioViewController
#synthesize scenarioTable = _scenarioTable;
#synthesize scenarioDetail = _scenarioDetail;
#synthesize scenarioId = _scenarioId;
#synthesize scenarioTableCellStyle = _scenarioTableCellStyle;
#synthesize dbObject = _dbObject;
#synthesize headerDateLabel = _headerDateLabel;
#synthesize headerTurfAcresLabel = _headerTurfAcresLabel;
#synthesize headerScenarioIDLabel = _headerScenarioIDLabel;
#synthesize headerDescriptionLabel = _headerDescriptionLabel;
#synthesize headerProductTypeLabel = _headerProductTypeLabel;
#synthesize headerTargetNitrogenLabel = _headerTargetNitrogenLabel;
#synthesize headerView = _headerView;
#synthesize synchronize = _synchronize;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
UIColor *_background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"main_login_bg.png"]];
self.view.backgroundColor = _background;
[_background release];
_scenarioTable.delegate = self;
_scenarioTable.dataSource = self;
// Set the table view to be rounded
[[self.scenarioTable layer] setCornerRadius:5.0];
[self loadDBAccessDatabase];
// [self didApplicationLaunchedFirstTime];
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIToolbar* _rightNavBarTools = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 260, 44)];
// create the array to hold the buttons, which then gets added to the toolbar
NSMutableArray* _rightNavBarButtons = [[NSMutableArray alloc] initWithCapacity:4];
UIBarButtonItem *_signout = [[UIBarButtonItem alloc] initWithTitle:#"Sign out" style:UIBarButtonItemStyleBordered target:self action:#selector(didApplicationLaunchedFirstTime)];
[_rightNavBarButtons addObject:_signout];
[_signout release];
UIBarButtonItem *_syncronize = [[UIBarButtonItem alloc] initWithTitle:#"Synchronize" style:UIBarButtonItemStyleBordered target:self action:#selector(syncronize)];
[_rightNavBarButtons addObject:_syncronize];
[_syncronize release];
UIBarButtonItem *_addNewScenario = [[UIBarButtonItem alloc]
initWithTitle:#"New TNT" style:UIBarButtonItemStyleBordered target:self
action:#selector(startNewScenario)];
[_rightNavBarButtons addObject:_addNewScenario];
[_addNewScenario release];
[_rightNavBarTools setItems:_rightNavBarButtons animated:NO];
[_rightNavBarButtons release];
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:_rightNavBarTools] autorelease];
[_rightNavBarTools release];
[self loadAllScenario];
}
- (void)viewWillAppear:(BOOL)animated
{
NSLog(#"%d", [self retainCount]);
[super viewWillAppear:animated];
[self loadAllScenario];
[self.scenarioTable reloadData];
}
- (void)viewDidUnload
{
[_scenarioTable release];
[_scenarioDetail release];
[_scenarioId release];
[_scenarioTableCellStyle release];
self.scenarioTable = nil;
self.scenarioDetail = nil;
self.scenarioId = nil;
self.scenarioTableCellStyle = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return YES;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return [self.scenarioId count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"scenarioTableCellStyle" owner:self options:nil];
cell = self.scenarioTableCellStyle;
self.scenarioTableCellStyle = nil;
}
if (indexPath.row % 2 == 0) {
cell.contentView.backgroundColor = [UIColor colorWithWhite:253.0/255 alpha:1];
} else {
cell.contentView.backgroundColor = [UIColor colorWithWhite:250.0/255 alpha:1];
}
NSDictionary * _scenarioDetailRow = [self.dbObject getScenarioDetail:[self.scenarioId objectAtIndex:indexPath.row]];
NSNumber* _tempNumber;
NSNumberFormatter* _formatter = [[NSNumberFormatter alloc] init];
NSString* _convertedNumber;
// Configure the cell...
_tempNumber = [_scenarioDetailRow objectForKey:#"scenarioid"];
[_formatter setNumberStyle:NSNumberFormatterDecimalStyle];
_convertedNumber = [_formatter stringForObjectValue:_tempNumber];
UILabel* _label = (UILabel *)[cell viewWithTag:1];
_label.text = _convertedNumber;
_label = (UILabel *)[cell viewWithTag:2];
NSString* _turftype = [_scenarioDetailRow objectForKey:#"turf"];
_label.text = _turftype;
_label = (UILabel *)[cell viewWithTag:3];
_tempNumber = [_scenarioDetailRow objectForKey:#"targetnitrogen"];
[_formatter setNumberStyle:NSNumberFormatterDecimalStyle];
_convertedNumber = [_formatter stringForObjectValue:_tempNumber];
_label.text = _convertedNumber;
_label = (UILabel *)[cell viewWithTag:4];
_tempNumber = [_scenarioDetailRow objectForKey:#"turfacre"];
[_formatter setNumberStyle:NSNumberFormatterDecimalStyle];
_convertedNumber = [_formatter stringForObjectValue:_tempNumber];
_label.text = _convertedNumber;
[_formatter release];
_label = (UILabel *)[cell viewWithTag:5];
NSString* _dateCreated = [_scenarioDetailRow objectForKey:#"datecreated"];
NSDateFormatter *inputFormatter = [[[NSDateFormatter alloc] init] autorelease];
[inputFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *_inputDateCreated = [inputFormatter dateFromString:_dateCreated];
NSDateFormatter *outputFormatter = [[[NSDateFormatter alloc] init] autorelease];
[outputFormatter setDateFormat:#"MM-dd-yyyy"];
NSString *_outputDateCreated = [outputFormatter stringFromDate:_inputDateCreated];
_label.text = _outputDateCreated;
_label = (UILabel *)[cell viewWithTag:6];
if (([_scenarioDetailRow objectForKey:#"description"] != nil) && ([_scenarioDetailRow objectForKey:#"description"] != (id)[NSNull null])){
NSString* _discription = [_scenarioDetailRow objectForKey:#"description"];
_label.text = _discription;
} else {
_label.text = [NSString stringWithString:#""];
}
return cell;
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
if (UIInterfaceOrientationIsLandscape(fromInterfaceOrientation))
{
// Move the plots into place for portrait
_headerScenarioIDLabel.frame = CGRectMake(-30, 2, 125, 20);
_headerDescriptionLabel.frame = CGRectMake(52, 2, 125, 20);
_headerProductTypeLabel.frame = CGRectMake(278, 2, 125, 20);
_headerTargetNitrogenLabel.frame = CGRectMake(368, 2, 125, 20);
_headerTurfAcresLabel.frame = CGRectMake(437, 2, 125, 20);
_headerDateLabel.frame = CGRectMake(545, 2, 125, 20);
}
else
{
// Move the plots into place for landscape
_headerScenarioIDLabel.frame = CGRectMake(-26, 2, 125, 20);
_headerDescriptionLabel.frame = CGRectMake(85, 2, 125, 20);
_headerProductTypeLabel.frame = CGRectMake(390, 2, 125, 20);
_headerTargetNitrogenLabel.frame = CGRectMake(526, 2, 125, 20);
_headerTurfAcresLabel.frame = CGRectMake(626, 2, 125, 20);
_headerDateLabel.frame = CGRectMake(759, 2, 125, 20);
}
}
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
_headerScenarioIDLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
_headerDateLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
_headerDescriptionLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
_headerProductTypeLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
_headerTargetNitrogenLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
_headerTurfAcresLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
BOOL isLandscape = UIDeviceOrientationIsLandscape(self.interfaceOrientation);
if (UIInterfaceOrientationIsLandscape(orientation) || isLandscape)
{
// Move the plots into place for landscape
_headerScenarioIDLabel.frame = CGRectMake(-26, 2, 125, 20);
_headerDescriptionLabel.frame = CGRectMake(85, 2, 125, 20);
_headerProductTypeLabel.frame = CGRectMake(390, 2, 125, 20);
_headerTargetNitrogenLabel.frame = CGRectMake(526, 2, 125, 20);
_headerTurfAcresLabel.frame = CGRectMake(626, 2, 125, 20);
_headerDateLabel.frame = CGRectMake(759, 2, 125, 20);
}
else
{
// Move the plots into place for portrait
_headerScenarioIDLabel.frame = CGRectMake(-30, 2, 125, 20);
_headerDescriptionLabel.frame = CGRectMake(52, 2, 125, 20);
_headerProductTypeLabel.frame = CGRectMake(278, 2, 125, 20);
_headerTargetNitrogenLabel.frame = CGRectMake(368, 2, 125, 20);
_headerTurfAcresLabel.frame = CGRectMake(437, 2, 125, 20);
_headerDateLabel.frame = CGRectMake(545, 2, 125, 20);
}
if(_headerView == nil) {
//allocate the view if it doesn't exist yet
_headerView = [[UIView alloc] init];
UIColor *_background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"toolbar_bkg.png"]];
_headerView.backgroundColor = _background;
[_background release];
_headerScenarioIDLabel.backgroundColor = [UIColor clearColor];
_headerScenarioIDLabel.opaque = NO;
_headerScenarioIDLabel.textColor = [UIColor whiteColor];
_headerScenarioIDLabel.font = [UIFont boldSystemFontOfSize:12];
_headerScenarioIDLabel.textAlignment = UITextAlignmentCenter;
_headerScenarioIDLabel.text = #"ID";
_headerDateLabel.backgroundColor = [UIColor clearColor];
_headerDateLabel.opaque = NO;
_headerDateLabel.textColor = [UIColor whiteColor];
_headerDateLabel.font = [UIFont boldSystemFontOfSize:12];
_headerDateLabel.textAlignment = UITextAlignmentCenter;
_headerDateLabel.text = #"Date";
_headerDescriptionLabel.backgroundColor = [UIColor clearColor];
_headerDescriptionLabel.opaque = NO;
_headerDescriptionLabel.textColor = [UIColor whiteColor];
_headerDescriptionLabel.font = [UIFont boldSystemFontOfSize:12];
_headerDescriptionLabel.textAlignment = UITextAlignmentCenter;
_headerDescriptionLabel.text = #"Description";
_headerProductTypeLabel.backgroundColor = [UIColor clearColor];
_headerProductTypeLabel.opaque = NO;
_headerProductTypeLabel.textColor = [UIColor whiteColor];
_headerProductTypeLabel.font = [UIFont boldSystemFontOfSize:12];
_headerProductTypeLabel.textAlignment = UITextAlignmentCenter;
_headerProductTypeLabel.text = #"Product Type";
_headerTargetNitrogenLabel.backgroundColor = [UIColor clearColor];
_headerTargetNitrogenLabel.opaque = NO;
_headerTargetNitrogenLabel.textColor = [UIColor whiteColor];
_headerTargetNitrogenLabel.font = [UIFont boldSystemFontOfSize:12];
_headerTargetNitrogenLabel.textAlignment = UITextAlignmentCenter;
_headerTargetNitrogenLabel.text = #"Target N";
_headerTurfAcresLabel.backgroundColor = [UIColor clearColor];
_headerTurfAcresLabel.opaque = NO;
_headerTurfAcresLabel.textColor = [UIColor whiteColor];
_headerTurfAcresLabel.font = [UIFont boldSystemFontOfSize:12];
_headerTurfAcresLabel.textAlignment = UITextAlignmentCenter;
_headerTurfAcresLabel.text = #"Turf Acres";
//add the button to the view
[_headerView addSubview:_headerScenarioIDLabel];
[_headerView addSubview:_headerDescriptionLabel];
[_headerView addSubview:_headerProductTypeLabel];
[_headerView addSubview:_headerTargetNitrogenLabel];
[_headerView addSubview:_headerTurfAcresLabel];
[_headerView addSubview:_headerDateLabel];
}
//return the view for the footer
return _headerView;
}
// specify the height of your footer section
- (CGFloat)tableView:(UITableView *)tableView
heightForHeaderInSection:(NSInteger)section {
//differ between your sections or if you
//have only on section return a static value
return 24;
}
- (CGFloat)tableView:(UITableView *)tableView
heightForFooterInSection:(NSInteger)section {
//differ between your sections or if you
//have only on section return a static value
return 14;
}
- (UIView *) tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
UIColor *_background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"toolbar_bkg.png"]];
UIView* _customView = [[[UIView alloc]initWithFrame:CGRectMake(10.0, 0.0, 300.0, 44.0)]autorelease];
_customView.backgroundColor = _background;
[_background release];
return _customView;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
ScenarioDetailViewController* _detailViewController = [[ScenarioDetailViewController alloc] initWithNibName:#"ScenarioDetailViewController" bundle:nil];
_detailViewController.dbObject = self.dbObject;
[_detailViewController setScenarioId:[self.scenarioId objectAtIndex:indexPath.row]];
[self.navigationController pushViewController:_detailViewController animated:YES];
[_detailViewController release];
}
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
// Updates the appearance of the Edit|Done button as necessary.
[super setEditing:editing animated:animated];
[self.scenarioTable setEditing:editing animated:YES];
// Disable the add button while editing.
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// must update the database before updating the tableView
// so that the tableView never has a row that's missing from the database
[self.dbObject deleteScenarioRow:[self.scenarioId objectAtIndex:indexPath.row]];
[self loadAllScenario];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
[self.scenarioTable reloadData];
}
}
- (void)dealloc {
[_synchronize release];
[_scenarioTable release];
[_scenarioDetail release];
[_scenarioId release];
[_scenarioTableCellStyle release];
[_headerDateLabel release];
[_headerTurfAcresLabel release];
[_headerScenarioIDLabel release];
[_headerDescriptionLabel release];
[_headerProductTypeLabel release];
[_headerTargetNitrogenLabel release];
[_headerView release];
[super dealloc];
}
// Called when an alertview button is touched
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
switch (buttonIndex) {
case 0:
{
NSLog(#"user not want to sync");
}
break;
case 1:
{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
_synchronize = [[TNSynchronize alloc] init];
_synchronize.delegate = self;
[_synchronize jesonRequest];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
break;
}
}
- (void) reloadAfterSyncronize {
[self loadAllScenario];
[self.scenarioTable reloadData];
}
#pragma mark - TNTScenarioViewController lifecycle methods
- (void) syncronize {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Syncronize process", nil)
message:NSLocalizedString(#"\n Syncronize process will be start and work in background.", nil)
delegate:self
cancelButtonTitle:NSLocalizedString(#"Cancel", nil)
otherButtonTitles:NSLocalizedString(#"Ok", nil), nil];
[alert show];
[alert release];
}
- (void) didApplicationLaunchedFirstTime {
LoginViewController *loginViewObj = [[[LoginViewController alloc] init] autorelease];
loginViewObj.dbObject = self.dbObject;
UINavigationController *navigationController = [[[UINavigationController alloc]
initWithRootViewController:loginViewObj] autorelease];
navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentModalViewController:navigationController animated:YES];
}
- (void)loadSynchronizeController {
[self.scenarioTable reloadData];
}
// This is Method to New Scenario
- (void) startNewScenario {
ScenarioDetailViewController* _detailViewController = [[ScenarioDetailViewController alloc] initWithNibName:#"ScenarioDetailViewController" bundle:nil];
[_detailViewController setScenarioId:[NSNumber numberWithInt:0]];
[self.navigationController pushViewController:_detailViewController animated:YES];
// [_detailViewController release];
}
// This Method use for Load Value of Scenario
- (NSMutableArray *) loadAllScenario {
// NSLog(#"%s", __FUNCTION__);
// First, test for existence.
NSArray* _paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* _documentsDirectory = [_paths objectAtIndex:0];
NSString* _writableConfigPath = [_documentsDirectory stringByAppendingPathComponent:#"Configuration.plist"];
NSMutableDictionary* _configFile = [[NSMutableDictionary alloc] initWithContentsOfFile:_writableConfigPath];
NSString* _loginStatus= [NSString stringWithString:[_configFile objectForKey:#"UserEmail"]];
[_configFile autorelease];
[self.scenarioId removeAllObjects];
if (!_dbObject) [self loadDBAccessDatabase];
self.scenarioId = [NSMutableArray arrayWithArray:[_dbObject getRelatedScenarioArray:_loginStatus]];
return self.scenarioId;
}
- (NSArray *) loadScenarioIDsIfEmpty {
// NSLog(#"%s", __FUNCTION__);
// First, test for existence.
NSArray* _paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* _documentsDirectory = [_paths objectAtIndex:0];
NSString* _writableConfigPath = [_documentsDirectory stringByAppendingPathComponent:#"Configuration.plist"];
NSMutableDictionary* _configFile = [[NSMutableDictionary alloc] initWithContentsOfFile:_writableConfigPath];
NSString* _loginStatus = [NSString stringWithString:[_configFile objectForKey:#"UserEmail"]];
[_configFile autorelease];
if (!_dbObject) [self loadDBAccessDatabase];
if (!self.scenarioId || ![self.scenarioId count]) self.scenarioId = [NSMutableArray arrayWithArray:[_dbObject getRelatedScenarioArray:_loginStatus]];
return self.scenarioId;
}
- (DBAccess *) loadDBAccessDatabase {
// NSLog(#"%s", __FUNCTION__);
_dbObject = [DBAccess sharedDBObjectAccess];
return _dbObject;
}
#end
This is the dealloc method as you asked
- (void)dealloc {
[_scenarioProductTable release];
[_attributePopover release];
[_gotMapRegion release];
[_gotTargetN release];
[_gotTurfAcres release];
[_gotTurftype release];
[_scenarioId release];
[_granularProductData release];
[_liquidProductData release];
[_areaGraphData release];
[_scenarioAppId release];
[_scenarioProductTableCellStyle release];
[_scenarioProductTable release];
[_carryOver release];
[_tempDiscription release];
[_scenarioDetailRow release];
[_turfacresTextField release];
[_discriptionTextField release];
[_footerView release];
[_headerView release];
[selectedTurftypeLabel release];
[selectedTargetNLabel release];
[selectedMapregionLabel release];
[selectedTurfAcresLabel release];
[_loginUser release];
[super dealloc];
}
and in this function it saying that i have the issue
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
ScenarioDetailViewController* _detailViewController = [[ScenarioDetailViewController alloc] initWithNibName:#"ScenarioDetailViewController" bundle:nil];
_detailViewController.dbObject = self.dbObject;
[_detailViewController setScenarioId:[self.scenarioId objectAtIndex:indexPath.row]];
[self.navigationController pushViewController:_detailViewController animated:YES];
[_detailViewController release];
}
and this line have 100% blame in the funnction
[self.navigationController pushViewController:_detailViewController animated:YES];
From the crash report, it is apparent that you are overreleasing an object (notice where it says the zombie CALayer has a retain count of -1; anything less than 0 is overreleased). My suggestion is either scour your code until you find it, use the Instruments tool 'Zombies' (which only works when profiling on the Simulator), or upgrade your project to ARC.
I would definitely recommend upgrading to ARC as the best choice. ARC streamlines your code and lowers your peak memory footprint, improving efficiency and greatly reducing the chances of a crash.
Edit:
To upgrade to ARC: (from the Xcode menu)
Edit -> Refactor -> Convert to Objective-C ARC...
(from Apple's Face Detection example project)
Edit 2:
In response to #Chris's answer:
In viewDidUnload you should only release objects that are created in viewDidLoad; also, you should usually only be setting IBOutlets to nil. For every time viewDidUnload is called, viewDidLoad will be called to recreate everything that was destroyed in viewDidUnload. So the lesson is in viewDidUnload, only nil out objects that are created in viewDidLoad. If you release something that isn't created in viewDidLoad, it won't be recreated when you return to that view, which can cause a crash.
Yet I don't think that is your problem here. viewDidUnload is not actually called when a view controller is destroyed (dealloc is called because the controller was popped from the navigation stack or the modal view controller was dismissed). viewDidUnload is only called when the application receives a memory warning- viewDidUnload's job is to release any objects that can be recreated later. Assuming you don't receive any memory warnings and you are just pushing/popping a view controller from the stack, the double release is viewDidUnload is not causing this problem (though it might cause one later).
Moral of the story:
Use ARC. It's not a toy, it really works. It won't 'lessen' your control over memory management- it removes the need for it. Apart from retain cycles (Brad Larson gives a nice explanation here: What kind of leaks does automatic reference counting in Objective-C not prevent or minimize?), ARC will take care of just about all of your memory management, especially leaks. You can still get rid of an object with:
someObject = nil;
so you can still control your memory footprint. #autoreleasepools are also still an option with ARC.
So, final moral of the story:
Use ARC.
- (void)viewDidUnload
{
[_scenarioTable release];
[_scenarioDetail release];
[_scenarioId release];
[_scenarioTableCellStyle release];
self.scenarioTable = nil;
self.scenarioDetail = nil;
self.scenarioId = nil;
self.scenarioTableCellStyle = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
Your -viewDidUnload method is double-releasing. First you explicitly release objects by referencing their instance variables, ie: [_scenarioTable release];. But you don't set the ivar to nil after doing that. So those instance variables still point to released objects.
Then you set the properties which are backed by those instance variables to nil. The properties are probably declared as using the retain memory management strategy. This means when you do self.scenarioTable = nil;, it will release the ivar associated with the property.
To fix this, just get rid of the 4 release calls at the top.
- (void)viewDidUnload
{
self.scenarioTable = nil;
self.scenarioDetail = nil;
self.scenarioId = nil;
self.scenarioTableCellStyle = nil;
[super viewDidUnload];
}
If you really want to keep those, change it to this:
- (void)viewDidUnload
{
[_scenarioTable release]; _scenarioTable = nil;
[_scenarioDetail release]; _scenarioDetail = nil;
[_scenarioId release]; _scenarioId = nil;
[_scenarioTableCellStyle release]; _scenarioTableCellStyle = nil;
[super viewDidUnload];
}
And this is why -viewDidUnload is deprecated in iOS 6.
like Rickay said, in your dealloc method and your viewDidUnload you release your 4 scenario objects twice. I've only used ARC but I'm pretty sure thats your issue

pushViewController:detail not pushing detailView

I had my app navigating views perfectly. Now, for some reason that I can't figure out, my detailView is not presenting on the pushViewController:detail method in my modal view.
I cannot figure out why it's not working any more. Any help would be appreciated. Thanks.
Here's the method:
- (void)tableView:(UITableView *)tView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tView deselectRowAtIndexPath:indexPath animated:YES];
if(indexPath.row == 0){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 1){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 2){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 3){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 4){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
}
Here's the class code. I'm not sure if I need to pass in a navigationController with modalView:
//
// ModalView.m
// DiningLog
//
// Created by Eric Rea on 10/10/11.
// Copyright 2011 Avid. All rights reserved.
//
#import "ModalView.h"
#import "DetailView.h"
#implementation ModalView
#synthesize tableView, excersizeName, numSets, time, restTime, dateFormatter, rating, excersizeArray, plistArray, numberWithBool;
-(IBAction) cancel:(id)sender{
[self dismissModalViewControllerAnimated:YES];
}
-(IBAction) save:(id)sender{
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"ExcersizeList.plist"];
// check to see if Data.plist exists in documents
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
// if not in documents, get property list from main bundle
plistPath = [[NSBundle mainBundle] pathForResource:#"Excersizes" ofType:#"plist"];
}
// read property list into memory as an NSData object
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSString *errorDesc = nil;
NSPropertyListFormat format;
// convert static property list into dictionary object
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
if (!temp)
{
NSLog(#"Error reading plist: %#, format: %d", errorDesc, format);
}
// assign values
self.plistArray = [NSMutableArray arrayWithArray:[temp objectForKey:#"Excersizes"]];
NSLog(#"The contents of plistArray is%#", plistArray);
// set the variables to the values in the text fields
self.excersizeArray = [[NSMutableArray alloc] initWithCapacity:4];
[excersizeArray addObject:excersizeName];
[excersizeArray addObject:numSets];
[excersizeArray addObject:time];
[excersizeArray addObject:restTime];
[plistArray addObject:excersizeArray];
// create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: plistArray, nil] forKeys:[NSArray arrayWithObjects: #"Excersizes", nil]];
NSString *error = nil;
// create NSData from dictionary
// NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
// check is plistData exists
if(plistDict)
{
// write plistData to our Data.plist file
[plistDict writeToFile:plistPath atomically:YES];
}
else
{
NSLog(#"Error in saveData: %#", error);
[error release];
}
[self dismissModalViewControllerAnimated:YES];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tView {
// Return the number of sections.
return 1;
}
-(void)setObject:(id)object forNum:(int)num{
if(num == 0){
self.excersizeName = object;
NSLog(#"res %#", self.excersizeName);
}else if(num == 1){
self.numSets = object;
NSLog(#"res %#", self.numSets);
}else if(num == 2){
self.time = object;
NSLog(#"res %#", self.time);
}else if(num == 3){
self.restTime = object;
NSLog(#"res %#", self.restTime);
}else if(num == 4){
self.rating = [object floatValue];
}
[tableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return 5;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier] autorelease];
}
if(indexPath.row == 0){
cell.textLabel.text = #"Excersize";
cell.detailTextLabel.text = excersizeName;
}
if(indexPath.row == 1){
cell.textLabel.text = #"Sets";
cell.detailTextLabel.text = numSets;
}
if(indexPath.row == 2){
cell.textLabel.text = #"Time";
cell.detailTextLabel.text = time;
}
if(indexPath.row == 3){
cell.textLabel.text = #"Rest";
cell.detailTextLabel.text = restTime;
}
if(indexPath.row == 4){
cell.textLabel.text = #"Rating";
cell.detailTextLabel.text = [NSString stringWithFormat:#"%f",rating];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (NSDateFormatter *)dateFormatter {
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
}
return dateFormatter;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tView deselectRowAtIndexPath:indexPath animated:YES];
if(indexPath.row == 0){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 1){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 2){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 3){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
if(indexPath.row == 4){
NSLog(#"hey");
DetailView * detail = [[DetailView alloc] initWithNumber:indexPath.row];
detail.delegate = self;
[[self navigationController] pushViewController:detail animated:YES];
}
}
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
}
return self;
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
#end
Have you debugged and checked that your navigationController isn't nil ?
I figured it out. I accidentally erased the method insertNewObject in my rootViewController. When I rewrote it, I forgot to add in ModalView * modal = [[ModalView alloc] init];. That was the problem.
Here's what the method looks like now that it's working:
- (void)insertNewObject {
ModalView * modal = [[ModalView alloc] init];
UINavigationController *controller = [[UINavigationController alloc] initWithRootViewController:modal];
[self presentModalViewController:controller animated:YES];
}

message sent to deallocated instance (probably UITableViewCell)

I know that a lot of folks have had this problem before and I've read a lot of suggested solutions, none of which has worked out for me. I'm working on a part of a larger project, involving three different views: the first view contains a UITableView with custom made cells called WeekdaySelectionWithPopoverCellController. This cell contains a label designating the weekday (Monday through Friday), a UISwitch and the following elements that are displayed or hidden respectively based on the state of the switch. If the switch is on, the cell looks like this:
----------------------------------------------------------------------
| Monday [ON/off] between ( N/A ) and ( N/A ) |
----------------------------------------------------------------------
If it's off it looks like this:
----------------------------------------------------------------------
| Monday [on/OFF] |
----------------------------------------------------------------------
The (N/A) elements are UIButtons. If the user hits one of those buttons a UIPopover with a date picker opens. The idea is that the user selects a time from the picker that should be displayed on the UIButtons instead of the (N/A):
----------------------------------------------------------------------
| Monday [ON/off] between ( 12:30 ) and ( 16:00 ) |
----------------------------------------------------------------------
The hiding of the elements on hitting the UISwitch works as does the display of the popover. However, if the user hits the "Done" button in the popover and the popover is dismissed the app crashes with the following error:
-[UITableViewCell isKindOfClass:]: message sent to deallocated instance 0xf42a100
Strangely enough the only place containing code that calls isKindOfClass is ModalTableViewController (the parent view of the popover and the custom cells) and the address of the instance displayed does not belong to it. Neither is it the address of the popover which only leaves the class of the custom cells (WeekdaySelectionWithPopoverCellController).
Let me give you the relevant parts of the ModalTableViewController.m:
#implementation ModalTableViewController
#synthesize mtvcNavigationBar;
#synthesize mtvcTableView;
#synthesize cell;
#synthesize lable;
#synthesize button;
// WeekdaySelectionWithPopoverCell
#synthesize wswpMainLabel;
#synthesize wswpFromLabel;
#synthesize wswpToLabel;
#synthesize wswpOClockFromLabel;
#synthesize wswpOClockToLabel;
#synthesize wswpSwitch;
#synthesize wswpFromValueButton;
#synthesize wswpToValueButton;
#synthesize popoverController;
// more code...
- (ModalTableViewController *)initWithParam:(NSString *)title andData:(NSArray *)myData andSelection:(NSArray *)selection {
[self initSwipeLeftNavigation];
mtvcNavigationBar.topItem.title = title;
mtvcSectionSize = [myData count];
mtvcSectionname = #"";
mtvcLabels = myData;
mtvcData = selection;
[mtvcLabels retain];
[mtvcData retain];
[otherValues retain];
mtvSingleton = [ModalTableViewSingleton sharedInstance];
return self;
}
// more code...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cellRet;
NSString *MyIdentifier = #"WeekdaySelectionWithPopoverCellController";
cellRet = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cellRet == nil) {
[[NSBundle mainBundle] loadNibNamed:MyIdentifier owner:self options:nil];
cellRet = self.cell;
}
NSDictionary *tempValues;
tempValues = [mtvcData objectAtIndex:indexPath.row];
wswpSwitch = (UISwitch *)[cellRet viewWithTag:2];
wswpSwitch.on = [[tempValues valueForKey:#"company_id"] isKindOfClass:[NSNull class]] ? false: true;
BOOL negatedState = !wswpSwitch.on;
NSLog(#"tempValues: %#", tempValues);
lable = (UILabel *)[cellRet viewWithTag:1];
lable.text = [NSString stringWithFormat:#"%#", [tempValues valueForKey:#"short"]];
lable.font = [UIFont boldSystemFontOfSize:16];
lable = (UILabel *)[cellRet viewWithTag:3];
lable.font = [UIFont boldSystemFontOfSize:16];
lable.text = [NSString stringWithFormat:#"%#", #"von"];
lable.hidden = negatedState;
lable = (UILabel *)[cellRet viewWithTag:5];
lable.text = [NSString stringWithFormat:#"%#", #"bis"];
lable.font = [UIFont boldSystemFontOfSize:16];
lable.hidden = negatedState;
lable = (UILabel *)[cellRet viewWithTag:7];
lable.text = #"Uhr";
lable.font = [UIFont boldSystemFontOfSize:16];
lable.hidden = negatedState;
lable = (UILabel *)[cellRet viewWithTag:8];
lable.text = #"Uhr";
lable.font = [UIFont boldSystemFontOfSize:16];
lable.hidden = negatedState;
button = (UIButton *)[cellRet viewWithTag:4];
[self setButtonLabel:button forKey:#"beginning" fromDict:tempValues];
button.hidden = negatedState;
/*
if (![[tempValues valueForKey:#"beginning"] isKindOfClass:[NSNull class]]) {
button.titleLabel.text = [NSString stringWithFormat:#"%#", [tempValues valueForKey:#"beginning"]];
} else {
button.titleLabel.text = #"k.A.";
}
*/
button = (UIButton *)[cellRet viewWithTag:6];
[self setButtonLabel:button forKey:#"until" fromDict:tempValues];
button.hidden = negatedState;
/*
if (![[tempValues valueForKey:#"until"] isKindOfClass:[NSNull class]]) {
button.titleLabel.text = [NSString stringWithFormat:#"%#", [tempValues valueForKey:#"until"]];
} else {
button.titleLabel.text = #"k.A.";
}
*/
self.cell = nil;
return cellRet;
}
- (void)setButtonLabel:(UIButton *)btn forKey:(NSString *)key fromDict:(NSDictionary *)dict {
[btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
NSString *text = [dict objectForKey:key];
if ([mtvSingleton.sharedData objectForKey:key]) {
[btn setTitle:[mtvSingleton.sharedData objectForKey:key] forState:UIControlStateNormal];
} else {
if ([text isKindOfClass:[NSNull class]] ||
[text isEqualToString:#""])
{
[btn setTitle:#"k.A." forState:UIControlStateNormal];
} else {
[btn setTitle:text forState:UIControlStateNormal];
}
}
}
// more code...
- (IBAction)switchButtonValueChanged:(id)sender
{
//[self changeDisplayState:wsdSwitch.on forObj:sender];
// UISwitch *tmp = (UISwitch *)sender;
UIView *v = (UIView *)sender;
do {
v = v.superview;
} while (![v isKindOfClass:[UITableViewCell class]]);
// WeekdaySelectionWithPopoverCellController *cell1 = (WeekdaySelectionWithPopoverCellController *)v;
cell = (UITableViewCell *)v;
wswpSwitch = (UISwitch *)[cell viewWithTag:2];
BOOL negatedState = !wswpSwitch.on;
lable = (UILabel *)[cell viewWithTag:3];
lable.hidden = negatedState;
lable = (UILabel *)[cell viewWithTag:5];
lable.hidden = negatedState;
lable = (UILabel *)[cell viewWithTag:7];
lable.hidden = negatedState;
lable = (UILabel *)[cell viewWithTag:8];
lable.hidden = negatedState;
button = (UIButton *)[cell viewWithTag:4];
button.hidden = negatedState;
button = (UIButton *)[cell viewWithTag:6];
button.hidden = negatedState;
/*
wswpSwitch = (UISwitch *)[cell1 viewWithTag:2];
BOOL negatedState = !wswpSwitch.on;
lable = (UILabel *)[cell1 viewWithTag:3];
lable.hidden = negatedState;
lable = (UILabel *)[cell1 viewWithTag:5];
lable.hidden = negatedState;
lable = (UILabel *)[cell1 viewWithTag:7];
lable.hidden = negatedState;
lable = (UILabel *)[cell1 viewWithTag:8];
lable.hidden = negatedState;
button = (UIButton *)[cell1 viewWithTag:4];
button.hidden = negatedState;
button = (UIButton *)[cell1 viewWithTag:6];
button.hidden = negatedState;
*/
}
#pragma mark - handlers
- (IBAction)toButtonHandler:(id)sender {
dppvc = [[DatePickerPopoverViewController alloc] initWithCaller:self andKey:#"beginning"];
UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:dppvc];
popover.delegate = self;
self.popoverController = popover;
[popover release];
[self.popoverController presentPopoverFromRect:[(UIButton *)sender frame]
inView:self.view
permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}
- (IBAction)fromButtonHandler:(id)sender {
dppvc = [[DatePickerPopoverViewController alloc] initWithCaller:self andKey:#"until"];
UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:dppvc];
popover.delegate = self;
self.popoverController = popover;
[popover release];
CGRect senderFrameRect = [(UIButton *)sender frame];
[self.popoverController presentPopoverFromRect:senderFrameRect
inView:self.view
permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}
#pragma mark - UIPopoverControllerDelegate
//---called when the user clicks outside the popover view---
- (BOOL)popoverControllerShouldDismissPopover:(UIPopoverController *)popoverController {
// NSLog(#"popover about to be dismissed");
return YES;
}
//---called when the popover view is dismissed---
- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController {
// NSLog(#"popover dismissed");
}
- (void)dismissPopover {
if (popoverController != nil) {
[popoverController dismissPopoverAnimated:YES];
NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
int i;
for (i = 0; i < [mtvcLabels count]; i++) {
[indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
}
[mtvcTableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:YES];
}
}
- (void)dealloc {
[mtvcSectionname release];
[mtvcLabels release];
[mtvcData release];
[cell release];
[super dealloc];
}
The crash occurs in main.m:
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// crashes:
int retVal = UIApplicationMain(argc, argv, nil, nil); // <--
[pool release];
return retVal;
}
I have enabled NSZombieEnabled, MallocStackLoggingNoComp and NSAutoreleaseFreedObjectCheckEnabled but the compiler doesn't give me any more information than what I posted.
I've spent the entire day trying to resolve this but to no avail. Any hint in the right direction is appreciated!
I've been able to take care of this particular error. The problem was that cellRet in cellForRowAtIndexPath had not been retained. The following snippet resolves the error mentioned above:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cellRet;
NSString *MyIdentifier = #"WeekdaySelectionWithPopoverCellController";
cellRet = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cellRet == nil) {
[[NSBundle mainBundle] loadNibNamed:MyIdentifier owner:self options:nil];
cellRet = self.cell;
[cellRet retain];
}
// ...
}
Now however, I'm stuck with a new, similar error. This time it says:
*** -[CALayer release]: message sent to deallocated instance 0xc656d30
The following topic has some more information on the problem: "[CALayer release]: message sent to deallocated instance" when dismissing modal view controller
I have tried to change the property of the popover view controller to assign instead of retain but that gave me the message sent to deallocated instance error again, this time for the popover view controller.
Somebody with an idea? TIA!
The way I usually handle this is to create a subclass of UITableViewCell for my custom cells. and use the nib. I create a custom init that loads the cell from the nib. as follows.
- (id)init
{
self = [[[[NSBundle mainBundle] loadNibNamed:#"NibName" owner:self options:nil] objectAtIndex:0] retain];
if (self)
{
// any further initialization
}
return self;
}
in the nib set the cell's class to your new class.
then to use your cell do the following.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CustomCell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell)
{
cell = [[[CustomCell alloc] init] autorelease];
}
// setup your cell
return cell;
}
You should definitely be using assign on your delegate properties.