message sent to deallocated instance (probably UITableViewCell) - objective-c

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.

Related

Managing multiple textview inside tableview

i have a tableview which required three textview for description. i have made a prototype cell containing text view with tag 1000.
i want to reuse this textview but the text of the textview changes when i scroll.
Some time Faraz take position of haider textview and sometime zaidi take position of faraz.
i try to give them unique tag also but still it doesnot help me.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellViewIdentifier = nil;
long section = indexPath.section;
UITableViewCell *cell;
if(section == kSocialStatusSection) {
if(indexPath.row < socialResult.socialStatus.count){
cellViewIdentifier = kCheckBoxItemCellViewIdentifier;
cellViewIdentifier = [cellViewIdentifier stringByAppendingString:langAppendString];
cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellViewIdentifier];
[cell setBackgroundColor:[UIColor clearColor]];
SocialStatus * socialStatus = [socialResult.socialStatus objectAtIndex:indexPath.row];
[cell setBackgroundColor:[UIColor clearColor]];
UILabel *titleLabel = (UILabel *) [cell viewWithTag:kTagTitleCellLabel];
// NSMutableDictionary *obj = [socialStatusArray objectAtIndex:indexPath.row];
[titleLabel setText:[LanguageUtilities isEnglishLanguage]?socialStatus.typeNameEn:socialStatus.typeNameAr];
UIButton *checkBox = (UIButton *) [cell viewWithTag:kTagCheckButton];
// checkBox.selected = NO;
if([socialStatus.selected boolValue]) {
checkBox.selected = YES;
}
else{
checkBox.selected = NO;
}
} else {
cellViewIdentifier = kDescriptionCellViewIdentifier;
cellViewIdentifier = [cellViewIdentifier stringByAppendingString:langAppendString];
cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellViewIdentifier];
[cell setBackgroundColor:[UIColor clearColor]];
GCPlaceholderTextView *textArea = (GCPlaceholderTextView *)[cell viewWithTag:kTagDescriptionTextArea];
textArea.placeholder =getLocalizedString(#"Description");
textArea.delegate = self;
textArea.text = #"FARAZ";
}
}
else if(section == kSocialStatusProblems){
if(indexPath.row < socialResult.socialProblems.count){
cellViewIdentifier = kCheckBoxItemCellViewIdentifier;
cellViewIdentifier = [cellViewIdentifier stringByAppendingString:langAppendString];
cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellViewIdentifier];
[cell setBackgroundColor:[UIColor clearColor]];
SocialProblem * socialProblem = [socialResult.socialProblems objectAtIndex:indexPath.row];
UILabel *titleLabel = (UILabel *) [cell viewWithTag:kTagTitleCellLabel];
// NSMutableDictionary *obj = [socialProblemsArray objectAtIndex:indexPath.row];
[titleLabel setText:[LanguageUtilities isEnglishLanguage]?socialProblem.typeNameEn:socialProblem.typeNameAr];
UIButton *checkBox = (UIButton *) [cell viewWithTag:kTagCheckButton];
if([socialProblem.selected boolValue]) {
checkBox.selected = YES;
}else{
checkBox.selected = NO;
}
} else {
cellViewIdentifier = kDescriptionCellViewIdentifier;
cellViewIdentifier = [cellViewIdentifier stringByAppendingString:langAppendString];
cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellViewIdentifier];
[cell setBackgroundColor:[UIColor clearColor]];
GCPlaceholderTextView *textArea = (GCPlaceholderTextView *)[cell viewWithTag:kTagDescriptionTextArea];
textArea.placeholder =getLocalizedString(#"Description");
textArea.delegate = self;
textArea.text = #"Haider";
}
}
else if(section == kProblemTypesSection){
if(indexPath.row < socialResult.socialProblemsTypes.count){
cellViewIdentifier = kCheckBoxItemCellViewIdentifier;
cellViewIdentifier = [cellViewIdentifier stringByAppendingString:langAppendString];
cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellViewIdentifier];
[cell setBackgroundColor:[UIColor clearColor]];
SocialProblemsType * socialProblemType = [socialResult.socialProblemsTypes objectAtIndex:indexPath.row];
UILabel *titleLabel = (UILabel *) [cell viewWithTag:kTagTitleCellLabel];
// NSMutableDictionary *obj = [problemTypeArray objectAtIndex:indexPath.row];
[titleLabel setText:[LanguageUtilities isEnglishLanguage]?socialProblemType.typeNameEn:socialProblemType.typeNameAr];
UIButton *checkBox = (UIButton *) [cell viewWithTag:kTagCheckButton];
if([socialProblemType.selected boolValue]) {
checkBox.selected = YES;
}else
{
checkBox.selected = NO;
}
} else {
cellViewIdentifier = kDescriptionCellViewIdentifier;
cellViewIdentifier = [cellViewIdentifier stringByAppendingString:langAppendString];
cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellViewIdentifier];
[cell setBackgroundColor:[UIColor clearColor]];
GCPlaceholderTextView * textArea= (GCPlaceholderTextView *)[cell viewWithTag:problemTypeTextViewTag];;
if (textArea != nil) {
textArea= (GCPlaceholderTextView *)[cell viewWithTag:problemTypeTextViewTag];
}else
{
textArea= (GCPlaceholderTextView *)[cell viewWithTag:kTagDescriptionTextArea];
[textArea setTag:problemTypeTextViewTag];
}
textArea.placeholder =getLocalizedString(#"Description");
textArea.delegate = self;
textArea.text = #"zaidi";
}
}
return cell;}
We can make do with an NSMutableArray object containing strings for each cell. You will have to fill the array with empty strings and use this info to fill the text field. It will be something like,
textView.text = [textViewStringsArr objectAtIndex:indexPath.row];
Since you're doing it programmatically within the view controller, you will have to set the view controller as your text view delegate. You can do
-(void)textViewDidEndEditing:(UITextView *)textView {
UITableViewCell *cell = (UITableViewCell*)textField.superview;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
... Since you've the index path, you can map it to an array.
[textViewStringsArr replaceObjectAtIndexPath:indexPath withObject:textView.text];
}
This would be the basic idea. Start with a mutable array of empty strings and modify them every time the text view is updated by replacing the original text with the new text. Hope this helps.

Uncheck (unfavorite) items in Favorites Table View

I have a tableview that displays a list of "favorited" items. Users favorite items in another tableview, and favorited items are listed in this tableview (FavoritesTableView.m).
For some reason, I can't get checked items (favorited items) to "uncheck" from the FavoritesTableView? What am I missing?
See the .m file below...
FavoritesViewController.h
#import <UIKit/UIKit.h>
#import "StrainTableCell.h"
#interface FavoritesViewController : UITableViewController
{
}
#property (strong, nonatomic) NSArray *favoritesArrayset;
#property (strong, nonatomic) IBOutlet UITableView *favoritesTable;
#property (nonatomic, strong) NSMutableArray * favoritesArray;
- (IBAction)backbuttonpressed: (UIBarButtonItem *)sender;
#end
FavoritesViewController.m
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
if (favoritesArray == Nil)
{
favoritesArray = [[NSMutableArray alloc] init];
}
else
{
[favoritesArray removeAllObjects];
}
NSData *dataSave = [[NSUserDefaults standardUserDefaults] objectForKey:#"strains"];
if (dataSave != Nil)
{
favoritesArrayset = [NSKeyedUnarchiver unarchiveObjectWithData:dataSave];
for (NSDictionary *item in favoritesArrayset)
{
BOOL isChecked = [[item objectForKey:#"checked"] boolValue];
if (isChecked == YES )
{
[favoritesArray addObject:item];
}
}
}
[favoritesTable reloadData];
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return favoritesArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSArray *Strains = [favoritesArray copy];
NSArray *dataArray = [favoritesArray copy];
static NSString *strainTableIdentifier = #"StrainTableCell";
StrainTableCell *cell = (StrainTableCell *)[tableView dequeueReusableCellWithIdentifier:strainTableIdentifier];
if (cell == nil)
{
cell = [[StrainTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strainTableIdentifier] ;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"StrainTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.titleLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Title"];
cell.descriptionLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Description"];
cell.ratingLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Rating"];
cell.ailmentLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Ailment"];
cell.actionLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Action"];
cell.ingestLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Ingestion"];
cell.whatCellamI = [NSNumber numberWithInt:indexPath.row];
NSMutableDictionary *item = [dataArray objectAtIndex:indexPath.row];
cell.textLabel.text = [item objectForKey:#"text"];
[item setObject:cell forKey:#"StrainTableCell"];
}
BOOL checked = [[item objectForKey:#"checked"] boolValue];
UIImage *image = (checked) ? [UIImage imageNamed:#"checked.png"] : [UIImage imageNamed:#"unchecked.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
button.frame = frame;
[button setBackgroundImage:image forState:UIControlStateNormal];
[button addTarget:self action:#selector(checkButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor = [UIColor clearColor];
cell.accessoryView = button;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
StrainDetailViewController *detailViewController = [[StrainDetailViewController alloc]
initWithNibName:#"StrainDetailViewController" bundle:nil];
detailViewController.title = [[favoritesArray objectAtIndex:indexPath.row] objectForKey:#"Title"];
detailViewController.strainDetail = [favoritesArray objectAtIndex:indexPath.row];
[self.navigationController pushViewController:detailViewController animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 82;
}
- (IBAction)backbuttonpressed:(id)sender
{
[self.view.window.rootViewController dismissViewControllerAnimated:YES completion:nil];
}
- (void)checkButtonTapped:(id)sender event:(id)event
{
NSLog(#"made it here and event is %#",event);
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.favoritesTable];
NSIndexPath * indexPath ;
indexPath = [self.favoritesTable indexPathForRowAtPoint: currentTouchPosition];
NSLog(#"indexpath is below");
NSLog(#"%#",indexPath);
if (indexPath != Nil)
{
NSMutableDictionary *item = [favoritesArray objectAtIndex:indexPath.row];
BOOL isItChecked = [[item objectForKey:#"checked"] boolValue];
/*
if (isItChecked == NO) {
NSMutableArray *tmpArray = [[NSMutableArray alloc] init];
NSMutableArray *tmpArray2 = [[NSMutableArray alloc] initWithArray:[favoritesArray allObjects]];
NSString *text1 = [item objectForKey:#"Title"];
for (NSDictionary * object in tmpArray2) {
NSString *text2 = [object objectForKey:#"Title"];
if (![text1 isEqualToString:text2]) {
[tmpArray addObject:object];
}
}
// [favoritesArray removeAllObjects];
favoritesArray = [tmpArray copy];
}
*/
NSMutableArray *quickArray = [[NSMutableArray alloc] initWithArray:favoritesArray];
[quickArray replaceObjectAtIndex:indexPath.row withObject:item];
[item setObject:[NSNumber numberWithBool:!isItChecked] forKey:#"checked"];
favoritesArray = [quickArray copy];
// [self.favoritesArray addObject:item];
// NSLog(#"you have added %d items to favorites", self.favoritesArray.count);
[favoritesTable reloadData];
}
#end
In your .h take one NSMutableDictionary and do property to it.
In your .m synthesize it,and in viewdidLoad alloc the Dictionary.
Now put this below code in CellForRowAtIndex
if([idDictonary objectForKey:[NSString stringWithFormat:#"%d",[indexPath row]]])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
and put this below code in DidSelectRowAtIndex
UITableViewCell *thisCell = [tableView cellForRowAtIndexPath:indexPath];
if (thisCell.accessoryType == UITableViewCellAccessoryNone)
{
thisCell.accessoryType = UITableViewCellAccessoryCheckmark;
[idDictonary setValue:[dataArray objectAtIndex:indexPath.row] forKey:[NSString stringWithFormat:#"%d",[indexPath row]]];
}
else
{
if([idDictonary objectForKey:[NSString stringWithFormat:#"%d",[indexPath row]]])
{
[idDictonary removeObjectForKey:[NSString stringWithFormat:#"%d",[indexPath row]]];
thisCell.accessoryType = UITableViewCellAccessoryNone;
}
}
[myTableView reloadData];
NSLog(#"idDictonary = %#",idDictonary);
i hope this will helps u Brittany...
Every time -tableView:cellForRowAtIndexPath: runs, you create a new button, set it to the desired properties and … throw it away. (Seems to be the running joke this week.) You have to use the existing button.

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"];

removeObjectAtIndex crashing the app

In the .h file I have set the below line.
NSMutableArray *repArray;
In the .m file I have placed the below lines.(I put just the required lines of code for this ex)
-(void)read_data_fromDB
{
objectsForCharacters = [[NSMutableDictionary alloc]init];
sqlite3 *db = [contactAppDelegate getNewDBConnection];
NSMutableString *query = nil;
query = [NSMutableString stringWithFormat:#"select representative, title, business_name, uid from corporate where profiler_type <> 'OWN_CORPORATE' order by representative asc"];
const char *sql = [query UTF8String];
sqlite3_stmt *selectAllStmt = nil;
if(sqlite3_prepare_v2(db,sql, -1, &selectAllStmt, NULL)!= SQLITE_OK)
NSAssert1(0,#"error preparing statement",sqlite3_errmsg(db));
else
{
repArray = [[NSMutableArray alloc]init];
businessArray = [[NSMutableArray alloc]init];
titleArray = [[NSMutableArray alloc]init];
uidArray = [[NSMutableArray alloc]init];
while(sqlite3_step(selectAllStmt)==SQLITE_ROW)
{
char *chrstr =(char *)sqlite3_column_text(selectAllStmt, 0);
if(chrstr !=NULL)
{
corpRepresentative = [NSString stringWithUTF8String:chrstr];
[repArray addObject:corpRepresentative];
}
chrstr =(char *)sqlite3_column_text(selectAllStmt, 1);
if(chrstr !=NULL)
{
corpTitle = [NSString stringWithUTF8String:chrstr];
[titleArray addObject:corpTitle];
}
chrstr =(char *)sqlite3_column_text(selectAllStmt, 2);
if(chrstr !=NULL)
{
corpBusiness_name = [NSString stringWithUTF8String:chrstr];
[businessArray addObject:corpBusiness_name];
}
chrstr =(char *)sqlite3_column_text(selectAllStmt, 3);
if(chrstr !=NULL)
{
corporteUid = [NSString stringWithUTF8String:chrstr];
[uidArray addObject:corporteUid];
}
}
}
sqlite3_finalize(selectAllStmt);
sqlite3_close(db);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
UILongPressGestureRecognizer *longPressGesture =
[[[UILongPressGestureRecognizer alloc]
initWithTarget:self action:#selector(longPress:)] autorelease];
[cell addGestureRecognizer:longPressGesture];
}
// Configure the cell...
UILabel *txtLbl = [[UILabel alloc]initWithFrame:CGRectMake(70, 0, 175, 26)];
//[txtLbl setBackgroundColor:[UIColor greenColor]];
[txtLbl setTextAlignment:UITextAlignmentLeft];
NSString *txtStr = [repArray objectAtIndex:indexPath.row];
UIFont *fontTxtLbl = [UIFont fontWithName: #"FuturaMdBT" size:16];
[txtLbl setFont:fontTxtLbl];
[txtLbl setText:txtStr];
[cell.contentView addSubview:txtLbl];
[txtLbl release];
UILabel *txtDetailLbl = [[UILabel alloc]initWithFrame:CGRectMake(70, 27, 175, 20)];
// [txtDetailLbl setBackgroundColor:[UIColor redColor]];
[txtDetailLbl setTextAlignment:UITextAlignmentLeft];
NSString *txtDetailStr = [titleArray objectAtIndex:indexPath.row];
UIFont *fontTxtDetailLbl = [UIFont fontWithName: #"Arial" size:12];
[txtDetailLbl setFont:fontTxtDetailLbl];
[txtDetailLbl setText:txtDetailStr];
[cell.contentView addSubview:txtDetailLbl];
[txtDetailLbl release];
UILabel *txtDetailLbl1 = [[UILabel alloc]initWithFrame:CGRectMake(70, 47, 175, 20)];
//[txtDetailLbl1 setBackgroundColor:[UIColor blueColor]];
[txtDetailLbl1 setTextAlignment:UITextAlignmentLeft];
NSString *txtDetailStr1 = [businessArray objectAtIndex:indexPath.row];
UIFont *fontTxtDetailLbl1 = [UIFont fontWithName: #"Arial" size:12];
[txtDetailLbl1 setFont:fontTxtDetailLbl1];
[txtDetailLbl1 setText:txtDetailStr1];
[cell.contentView addSubview:txtDetailLbl1];
[txtDetailLbl1 release];
// cell.textLabel.text = [repArray objectAtIndex:indexPath.row];
//cell.detailTextLabel.text = [titleArray objectAtIndex:indexPath.row];
cell.imageView.image=[imagearray objectAtIndex:indexPath.row];
UIView *viewSelected = [[[UIView alloc] init] autorelease];
viewSelected.backgroundColor = [UIColor colorWithRed:224.0/255.0
green:229.0/255.0
blue:241.0/255.0
alpha:1.0];
cell.selectedBackgroundView = viewSelected;
cell.textLabel.highlightedTextColor=[UIColor colorWithRed:46.0/255.0
green:77.0/255.0
blue:141.0/255.0
alpha:1.0];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *tempUID = [uidArray objectAtIndex:indexPath.row];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:tempUCID forKey:#"corpUcid"];
[prefs setObject:#"PROFILER" forKey:#"selProfiler"];
CorpPrevFront *corpPrevFront = [[CorpPrevFront alloc]initWithNibName:#"CorpPrevFront" bundle:nil];
[self.navigationController pushViewController:corpPrevFront animated:NO];
[corpPrevFront release];
[tableView deselectRowAtIndexPath:indexPath animated:NO];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//FOR VIEW
if (buttonIndex == 1 && [alertView tag] == 1) {
// IT WILL BE MATCH ON CorpPrevFront CLASS
}
//FOR DELETE
if(buttonIndex == 2 && [alertView tag] == 1){
} else if(buttonIndex == 1 && [alertView tag] == 2){
DeleteProfiler *delProfiler = [[DeleteProfiler alloc]init];
BOOL del = [delProfiler deleteProfiler:selectedCpUid];
//[delProfiler deleteProfiler:selectedCpUcid];
if (del == YES) {
[repArray removeObjectAtIndex:selectedIndexPath.section];
[businessArray removeObjectAtIndex:selectedIndexPath.row];
[titleArray removeObjectAtIndex:selectedIndexPath.row];
[ucidArray removeObjectAtIndex:selectedIndexPath.row];
[self.corporateTable reloadData];
}
}
}
I am trying to delete an array element from a method. If I execute the below line then the app crashes automatically in my iPod Touch. But it works fine in simulator without any errors.
[repArray removeObjectAtIndex:selectedIndexPath.row];
or
[repArray removeObjectAtIndex:0];
both crashes the app even if I have more than one elements in array.
When you app crashes like that, 99% of the time you are trying to remove an object beyond the bounds of array.

Object is deallocated don't know why?

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.