drilldown tableview - objective-c

I have a project I am working on and it requires drill down UITableView. i have adapted my code to storyboard and it drills down fine from the first UITableView to the second UITableView but when I select the rows in the second UITableView I only get one of the arrays. when selecting any other row it just shows the detail for one of the rows. i know the description is vague so I am including my codes for more clarification. any help is truly appreciated.
TeamTable.m
#implementation TeamTable
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)dealloc
{
[super dealloc];
}
- (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];
teamArray = [[NSMutableArray alloc] init];
[teamArray addObject:#"East Cobb"];
[teamArray addObject:#"West Cobb"];
[teamArray addObject:#"Buckhead Thunder"];
[teamArray addObject:#"Fulton East"];
[teamArray addObject:#"Atlanta Braves"];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#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 [teamArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
UIImageView *imageView = [[UIImageView alloc] initWithFrame:cell.frame];
UIImage *image = [UIImage imageNamed:#"bgp.png"];
imageView.image = image;
cell.backgroundView = imageView;
[[cell textLabel] setBackgroundColor:[UIColor clearColor]];
[[cell detailTextLabel] setBackgroundColor:[UIColor clearColor]];
cell.textLabel.text = [[teamArray objectAtIndex:indexPath.row] autorelease];
return cell;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([[segue identifier] isEqualToString:#"Table"]){
TeamTable1 *teams = [segue destinationViewController];
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
if ([[teamArray objectAtIndex:indexPath.row] isEqual:#"East Cobb"]) {
teams.teamsInt = 0;
[teams setTitle:[teamArray objectAtIndex:indexPath.row]];
}
if ([[teamArray objectAtIndex:indexPath.row] isEqual:#"West Cobb"]) {
teams.teamsInt = 1;
[teams setTitle:[teamArray objectAtIndex:indexPath.row]];
}
if ([[teamArray objectAtIndex:indexPath.row] isEqual:#"Buckhead Thunder"]) {
teams.teamsInt = 2;
[teams setTitle:[teamArray objectAtIndex:indexPath.row]];
}
if ([[teamArray objectAtIndex:indexPath.row] isEqual:#"Fulton East"]) {
teams.teamsInt = 3;
[teams setTitle:[teamArray objectAtIndex:indexPath.row]];
}
if ([[teamArray objectAtIndex:indexPath.row] isEqual:#"Atlanta Braves"]) {
teams.teamsInt = 4;
[teams setTitle:[teamArray objectAtIndex:indexPath.row]];
}
}
}
#end
second table .h file
#interface TeamTable1 : UITableViewController{
NSMutableArray *eastCobbArray;
NSMutableArray *westCobbArray;
NSMutableArray *buckheadThunderArray;
NSMutableArray *fultonEastArray;
NSMutableArray *atlantaBravesArray;
NSMutableArray *sectionArray;
NSMutableArray *data;
int teamsInt;
}
#property int teamsInt;
- (void) makeData;
#end
second table .m file
#implementation TeamTable1
#synthesize teamsInt;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)dealloc
{
[sectionArray release];
[data release];
[eastCobbArray release];
[westCobbArray release];
[buckheadThunderArray release];
[fultonEastArray release];
[atlantaBravesArray release];
[super dealloc];
}
- (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{
[self makeData];
[super viewDidLoad];
}
- (void) makeData
{
data = [[NSMutableArray alloc] init];
sectionArray = [[NSMutableArray alloc] init];
eastCobbArray = [[NSMutableArray alloc] init];
westCobbArray = [[NSMutableArray alloc] init];
buckheadThunderArray = [[NSMutableArray alloc] init];
fultonEastArray = [[NSMutableArray alloc] init];
atlantaBravesArray = [[NSMutableArray alloc] init];
if (teamsInt == 0) {
[sectionArray addObject:#"East Cobb"];
}
if (teamsInt == 1) {
[sectionArray addObject:#"West Cobb"];
}
if (teamsInt == 2) {
[sectionArray addObject:#"Buckhead Thunder"];
}
if (teamsInt == 3) {
[sectionArray addObject:#"Fulton East"];
}
if (teamsInt == 4) {
[sectionArray addObject:#"Atlanta Braves"];
}
[eastCobbArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Coaches", #"name" , #"image1.JPG", #"image" , #"Mark Bayle 3rd Base\nSusane Ballor First Base\nJim Thally Pitching\nSam Bradley Batting", #"description", nil]];
[eastCobbArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Team Outlook", #"name" , #"image2.jpg", #"image" , #"our team has won 26 out of the 35 and it is in first place. We have 2 players on DL and have recalled two players to replace them.", #"description", nil]];
[eastCobbArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Schedule", #"name" , #"image3.jpg", #"image" , #"Sun June 30 VS Thunders # Home\nMon June 31 VS Braves # away\nTue July 1 VS East Cobb # Home", #"description", nil]];
[eastCobbArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Upcomming Events", #"name" , #"image4.jpg", #"image" , #"This is the list of the upcomming events for the month of july:\nJuly 1st:\nBake them all.\nJuly 2nd:\nFamily reunion\nJuly 3rd:\nSuppliers convention.", #"description", nil]];
[eastCobbArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Roster", #"name" , #"image5.jpg", #"image" , #"Jim this 17\nTim duncan 22\nJim thalos 21\nFredrick nitche 24\n", #"description", nil]];
[westCobbArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Coaches", #"name" , #"image1.JPG", #"image" , #"Mark Bayle 3rd Base\nSusane Ballor First Base\nJim Thally Pitching\nSam Bradley Batting", #"description", nil]];
[westCobbArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Team Outlook", #"name" , #"image2.jpg", #"image" , #"our team has won 26 out of the 35 and it is in first place. We have 2 players on DL and have recalled two players to replace them.", #"description", nil]];
[westCobbArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Schedule", #"name" , #"image3.jpg", #"image" , #"Sun June 30 VS Thunders # Home\n Mon June 31 VS Braves # away \n Tue July 1 VS East Cobb # Home \n", #"description", nil]];
[westCobbArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Upcomming Events", #"name" , #"image4.jpg", #"image" , #"This is the list of the upcomming events for the month of july:\nJuly 1st:\nBake them all.\nJuly 2nd:\nFamily reunion\nJuly 3rd:\nSuppliers convention.", #"description", nil]];
[westCobbArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Roster", #"name" , #"image5.jpg", #"image" , #"Jim this 17\nTim duncan 22\nJim thalos 21\nFredrick nitche 24\n", #"description", nil]];
[buckheadThunderArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Coaches", #"name" , #"image1.JPG", #"image" , #"Mark Bayle 3rd Base\nSusane Ballor First Base\nJim Thally Pitching\nSam Bradley Batting", #"description", nil]];
[buckheadThunderArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Team Outlook", #"name" , #"image2.jpg", #"image" , #"our team has won 26 out of the 35 and it is in first place. We have 2 players on DL and have recalled two players to replace them.", #"description", nil]];
[buckheadThunderArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Schedule", #"name" , #"image3.jpg", #"image" , #"Sun June 30 VS Thunders # Home \n MOn June 31 VS Braves # away \n Tue July 1 VS East Cobb # Home \n", #"description", nil]];
[buckheadThunderArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Upcomming Events", #"name" , #"image4.jpg", #"image" , #"This is the list of the upcomming events for the month of july:\nJuly 1st:\nBake them all.\nJuly 2nd:\nFamily reunion\nJuly 3rd:\nSuppliers convention.", #"description", nil]];
[buckheadThunderArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Roster", #"name" , #"image5.jpg", #"image" , #"Jim this 17\nTim duncan 22\nJim thalos 21\nFredrick nitche 24\n", #"description", nil]];
[fultonEastArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Coaches", #"name" , #"image1.JPG", #"image" , #"Mark Bayle 3rd Base\nSusane Ballor First Base\nJim Thally Pitching\nSam Bradley Batting", #"description", nil]];
[fultonEastArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Team Outlook", #"name" , #"image2.jpg", #"image" , #"our team has won 26 out of the 35 and it is in first place. We have 2 players on DL and have recalled two players to replace them.", #"description", nil]];
[fultonEastArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Schedule", #"name" , #"image3.jpg", #"image" , #"Sun June 30 VS Thunders # Home \n MOn June 31 VS Braves # away \n Tue July 1 VS East Cobb # Home \n", #"description", nil]];
[fultonEastArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Upcomming Events", #"name" , #"image4.jpg", #"image" , #"This is the list of the upcomming events for the month of july:\nJuly 1st:\nBake them all.\nJuly 2nd:\nFamily reunion\nJuly 3rd:\nSuppliers convention.", #"description", nil]];
[fultonEastArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Roster", #"name" , #"image5.jpg", #"image" , #"Jim this 17\nTim duncan 22\nJim thalos 21\nFredrick nitche 24\n", #"description", nil]];
[atlantaBravesArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Coaches", #"name" , #"image1.JPG", #"image" , #"Mark Bayle 3rd Base\nSusane Ballor First Base\nJim Thally Pitching\nSam Bradley Batting", #"description", nil]];
[atlantaBravesArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Team Outlook", #"name" , #"image2.jpg", #"image" , #"our team has won 26 out of the 35 and it is in first place. We have 2 players on DL and have recalled two players to replace them.", #"description", nil]];
[atlantaBravesArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Schedule", #"name" , #"image3.jpg", #"image" , #"Sun June 30 VS Thunders # Home\nMon June 31 VS Braves # away\nTue July 1 VS East Cobb # Home\n", #"description", nil]];
[atlantaBravesArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Upcomming Events", #"name" , #"image4.jpg", #"image" , #"This is the list of the upcomming events for the month of july:\nJuly 1st:\nBake them all.\nJuly 2nd:\nFamily reunion\nJuly 3rd:\nSuppliers convention.", #"description", nil]];
[atlantaBravesArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Roster", #"name" , #"image5.jpg", #"image" , #"Jim this 17\nTim duncan 22\nJim thalos 21\nFredrick nitche 24\n", #"description", nil]];
if (teamsInt == 0) {
[data addObject:eastCobbArray];
}
if (teamsInt == 1) {
[data addObject:westCobbArray];
}
if (teamsInt == 2) {
[data addObject:buckheadThunderArray];
}
if (teamsInt == 3) {
[data addObject:fultonEastArray];
}
if (teamsInt == 4) {
[data addObject:atlantaBravesArray];
}
}
- (void)viewDidUnload{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [sectionArray objectAtIndex:section];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
// Return the number of sections.
return [sectionArray count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [[data objectAtIndex:section] count];
[self.tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell1";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
UIImageView *imageView = [[UIImageView alloc] initWithFrame:cell.frame];
UIImage *image = [UIImage imageNamed:#"bgp.png"];
imageView.image = image;
cell.backgroundView = imageView;
[[cell textLabel] setBackgroundColor:[UIColor clearColor]];
[[cell detailTextLabel] setBackgroundColor:[UIColor clearColor]];
cell.textLabel.text = [[[data objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:#"name"];
return cell;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([[segue identifier] isEqualToString:#"Detail"]){
TeamDetail *teamDetail = [segue destinationViewController];
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
if (teamsInt == 0)
{
teamDetail.teamImageString = [[NSString alloc] initWithString:[[eastCobbArray objectAtIndex:indexPath.row] objectForKey:#"image"]];
teamDetail.teamTextString = [[NSString alloc] initWithString:[[eastCobbArray objectAtIndex:indexPath.row] objectForKey:#"description"]];
teamDetail.title = [[NSString alloc] initWithString:[[eastCobbArray objectAtIndex:indexPath.row] objectForKey:#"name"]];
}
if (teamsInt == 1)
{
teamDetail.teamImageString = [[NSString alloc] initWithString:[[westCobbArray objectAtIndex:indexPath.row] objectForKey:#"image"]];
teamDetail.teamTextString = [[NSString alloc] initWithString:[[westCobbArray objectAtIndex:indexPath.row] objectForKey:#"description"]];
teamDetail.title = [[NSString alloc] initWithString:[[westCobbArray objectAtIndex:indexPath.row] objectForKey:#"name"]];
}
if (teamsInt == 2)
{
teamDetail.teamImageString = [[NSString alloc] initWithString:[[buckheadThunderArray objectAtIndex:indexPath.row] objectForKey:#"image"]];
teamDetail.teamTextString = [[NSString alloc] initWithString:[[buckheadThunderArray objectAtIndex:indexPath.row] objectForKey:#"description"]];
teamDetail.title = [[NSString alloc] initWithString:[[buckheadThunderArray objectAtIndex:indexPath.row] objectForKey:#"name"]];
}
if (teamsInt == 3)
{
teamDetail.teamImageString = [[NSString alloc] initWithString:[[fultonEastArray objectAtIndex:indexPath.row] objectForKey:#"image"]];
teamDetail.teamTextString = [[NSString alloc] initWithString:[[fultonEastArray objectAtIndex:indexPath.row] objectForKey:#"description"]];
teamDetail.title = [[NSString alloc] initWithString:[[fultonEastArray objectAtIndex:indexPath.row] objectForKey:#"name"]];
}
if (teamsInt == 4)
{
teamDetail.teamImageString = [[NSString alloc] initWithString:[[atlantaBravesArray objectAtIndex:indexPath.row] objectForKey:#"image"]];
teamDetail.teamTextString = [[NSString alloc] initWithString:[[atlantaBravesArray objectAtIndex:indexPath.row] objectForKey:#"description"]];
teamDetail.title = [[NSString alloc] initWithString:[[atlantaBravesArray objectAtIndex:indexPath.row] objectForKey:#"name"]];
}
}
}
#end
TeamDetail.h
#interface TeamDetail : UIViewController{
IBOutlet UIImageView *teamImage;
IBOutlet UITextView *teamText;
NSString *teamImageString;
NSString *teamTextString;
}
#property (nonatomic, retain) NSString *teamImageString;
#property (nonatomic, retain) NSString *teamTextString;
#end
TeamDetail.m
#implementation TeamDetail
#synthesize teamImageString, teamTextString;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bcp.png"]];
teamImage.image = [UIImage imageNamed:teamImageString];
teamText.text = teamTextString;
// Do any additional setup after loading the view.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
now the connections and segue identifiers are fine and working it drills down all the way to detailview but only shows the first array information and sections and the rest of the arrays are not showing.
thanks in advance for your help
adrian

Anyway it seems that I find your mistake )
You obtain item like this, right:
if (teamsInt == 0)
{
teamDetail.teamImageString = [[NSString alloc] initWithString:[[eastCobbArray objectAtIndex:indexPath.row] objectForKey:#"image"]];
teamDetail.teamTextString = [[NSString alloc] initWithString:[[eastCobbArray objectAtIndex:indexPath.row] objectForKey:#"description"]];
teamDetail.title = [[NSString alloc] initWithString:[[eastCobbArray objectAtIndex:indexPath.row] objectForKey:#"name"]];
}
But look carefully - you use indexPath.row but should use indexPath.section instead! Your row is always 0.
Try this (ready for copy-paste ;)):
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([[segue identifier] isEqualToString:#"Detail"]){
TeamDetail *teamDetail = [segue destinationViewController];
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
if (teamsInt == 0)
{
teamDetail.teamImageString = [[NSString alloc] initWithString:[[eastCobbArray objectAtIndex:indexPath.section] objectForKey:#"image"]];
teamDetail.teamTextString = [[NSString alloc] initWithString:[[eastCobbArray objectAtIndex:indexPath.section] objectForKey:#"description"]];
teamDetail.title = [[NSString alloc] initWithString:[[eastCobbArray objectAtIndex:indexPath.section] objectForKey:#"name"]];
}
if (teamsInt == 1)
{
teamDetail.teamImageString = [[NSString alloc] initWithString:[[westCobbArray objectAtIndex:indexPath.section] objectForKey:#"image"]];
teamDetail.teamTextString = [[NSString alloc] initWithString:[[westCobbArray objectAtIndex:indexPath.section] objectForKey:#"description"]];
teamDetail.title = [[NSString alloc] initWithString:[[westCobbArray objectAtIndex:indexPath.section] objectForKey:#"name"]];
}
if (teamsInt == 2)
{
teamDetail.teamImageString = [[NSString alloc] initWithString:[[buckheadThunderArray objectAtIndex:indexPath.section] objectForKey:#"image"]];
teamDetail.teamTextString = [[NSString alloc] initWithString:[[buckheadThunderArray objectAtIndex:indexPath.section] objectForKey:#"description"]];
teamDetail.title = [[NSString alloc] initWithString:[[buckheadThunderArray objectAtIndex:indexPath.section] objectForKey:#"name"]];
}
if (teamsInt == 3)
{
teamDetail.teamImageString = [[NSString alloc] initWithString:[[fultonEastArray objectAtIndex:indexPath.section] objectForKey:#"image"]];
teamDetail.teamTextString = [[NSString alloc] initWithString:[[fultonEastArray objectAtIndex:indexPath.section] objectForKey:#"description"]];
teamDetail.title = [[NSString alloc] initWithString:[[fultonEastArray objectAtIndex:indexPath.section] objectForKey:#"name"]];
}
if (teamsInt == 4)
{
teamDetail.teamImageString = [[NSString alloc] initWithString:[[atlantaBravesArray objectAtIndex:indexPath.section] objectForKey:#"image"]];
teamDetail.teamTextString = [[NSString alloc] initWithString:[[atlantaBravesArray objectAtIndex:indexPath.section] objectForKey:#"description"]];
teamDetail.title = [[NSString alloc] initWithString:[[atlantaBravesArray objectAtIndex:indexPath.section] objectForKey:#"name"]];
}
}
}
p.s Consider about refactoring your code.
Do not add objects to array, create it in one string like:
teamArray = [[NSMutableArray alloc] initWithObjects:#"East Cobb", #"West Cobb", #"Buckhead Thunder", #"Fulton East", #"Atlanta Braves", nil];
or:
teamArray = #[#"East Cobb", #"West Cobb", #"Buckhead Thunder", #"Fulton East", #"Atlanta Braves"];
Use switch instaed of if() with numerical values
> teams.teamsInt = indexPath.row;
> switch (indexPath.row) {
> case:0
> teams.title = [teamArray objectAtIndex:indexPath.row];
> break;
> //and so on

Related

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.

NSRangeException error... NSDictionary, NSArray, UISearchBar

I am quite new with Objective C and I have been having trouble a a little while and I have been looking over answers, watching tutorials, and I have not been able to find a solution to my problem. Maybe its right in front of my face and I am not seeing it...I think it has something that has to do with the NSRange of my UISearch Bar. But I am not 100% sure.
I am trying to search through array that has the keys of my dictionary of countries, I have set up several NSLogs and I see that the keys are going into the array I have setup to save them in and then i get the error below...
So to my understanding of this, it is counting countryKeys which has 5, so index 4 should exist, should it not? but then it shows 0 .. 3, So I this is why I am thinking i am using NSRange incorrectly. I have watched some UISearchBar and For loop tutorials so far and i am understanding For loops and them better i guess I need to figure out NSRange then.
Let me know if you don't understand my thought process or anything that I mentioned..
Filtered Countries (
ATE,
ARE,
USA,
JAP,
CAN
)
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 4 beyond bounds [0 .. 3]'
-
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize dictTableView, mySearchBar, countriesInRegion, filteredCountries, isFiltered, regionCodes, countryKey, countryKeys, countryInfo, sortedKeysArray, regionCode, dict1;
- (void)viewDidLoad
{
[super viewDidLoad];
dict1 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *subDict = [[NSMutableDictionary alloc] initWithObjects:[NSArray arrayWithObjects:#"United States",#"US",#"USA", #"NAC", nil]
forKeys: [NSArray arrayWithObjects:#"countryName", #"countryAbbrev", #"countryID", #"countryRegion", nil]];
[dict1 setObject:subDict forKey:#"USA"];
subDict = [[NSMutableDictionary alloc] initWithObjects:[NSArray arrayWithObjects:#"Canada", #"CA", #"CAN", #"NAC", nil]
forKeys: [NSArray arrayWithObjects:#"countryName", #"countryAbbrev", #"countryID", #"countryRegion", nil]];
[dict1 setObject:subDict forKey:#"CAN"];
subDict = [[NSMutableDictionary alloc] initWithObjects:[NSArray arrayWithObjects:#"Japan", #"JP", #"JAP", #"EAS", nil]
forKeys: [NSArray arrayWithObjects:#"countryName", #"countryAbbrev", #"countryID", #"countryRegion", nil]];
[dict1 setObject:subDict forKey:#"JAP"];
subDict = [[NSMutableDictionary alloc] initWithObjects:[NSArray arrayWithObjects:#"United Arab Emirates", #"AE", #"ARE", #"MEA", nil]
forKeys: [NSArray arrayWithObjects:#"countryName", #"countryAbbrev", #"countryID", #"countryRegion", nil]];
[dict1 setObject:subDict forKey:#"ARE"];
subDict = [[NSMutableDictionary alloc] initWithObjects:[NSArray arrayWithObjects:#"Antigua and Barbuda", #"AG", #"ATE", #"LCN", nil]
forKeys: [NSArray arrayWithObjects:#"countryName", #"countryAbbrev", #"countryID", #"countryRegion", nil]];
[dict1 setObject:subDict forKey:#"ATE"];
regionCodes = [[NSMutableDictionary alloc] init];
countryKeys = [dict1 allKeys];
NSLog(#"countryKeys %#", countryKeys);
sortedKeysArray = [countryKeys sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)];
for (int i = 0; i < [sortedKeysArray count]; i++) {
countryKey = [sortedKeysArray objectAtIndex:i];
countryInfo = [dict1 objectForKey:countryKey]; // NSLog(#"returning countryKey to countryInfo %#", countryInfo);
regionCode = [countryInfo objectForKey:#"countryRegion"]; // NSLog(#" adding countryRegion Key to regionCode %#", regionCode);
// NSLog(#"the contents of countryInfo is %#", countryInfo);
if (![regionCodes objectForKey:regionCode]) {
countriesInRegion = [[NSMutableArray alloc] init];
[regionCodes setObject:countriesInRegion forKey:regionCode];
[countriesInRegion addObject:countryInfo]; // NSLog(#"if adding countryInfo to initialCountries %#", countryInfo);
}
else{
countriesInRegion = [regionCodes objectForKey:regionCode];
[countriesInRegion addObject:countryInfo]; // NSLog(#"else adding countryInfo to initialCountries %#", countryInfo);
}
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (isFiltered == NO)
{
return countryInfo.count;
}
else
{
return filteredCountries.count;
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSArray *sortKey = [regionCodes allKeys];
sortedKeysArray = [sortKey sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)];
return [sortedKeysArray objectAtIndex:section];
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
NSString *regionKey = [[regionCodes allKeys] objectAtIndex:section];
countriesInRegion = [regionCodes objectForKey:regionKey];
if (isFiltered == NO)
{
return countriesInRegion.count;
}
else
{
return filteredCountries.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
UITableViewCell *cell = nil;
cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:#"Cell"];
UILabel *countryNameLabel = [[UILabel alloc] initWithFrame:(CGRectMake(10, 0, 220, 44))];
[countryNameLabel setBackgroundColor:[UIColor clearColor]];
UILabel *countryAbbrevLabel = [[UILabel alloc] initWithFrame:(CGRectMake(230, 0, 75, 44))];
[countryNameLabel setBackgroundColor:[UIColor clearColor]];
UILabel *countryIDLabel = [[UILabel alloc] initWithFrame:(CGRectMake(275, 0, 50, 44))];
[countryNameLabel setBackgroundColor:[UIColor clearColor]];
[cell.contentView addSubview:countryNameLabel];
[cell.contentView addSubview:countryAbbrevLabel];
[cell.contentView addSubview:countryIDLabel];
}
NSArray *regionKeys = [regionCodes allKeys];
NSString *regionKey = [regionKeys objectAtIndex:indexPath.section];
countriesInRegion = [regionCodes objectForKey:regionKey];
NSLog(#"Countries in Region %#", countriesInRegion);
countryInfo = [countriesInRegion objectAtIndex:indexPath.row];
NSArray *subviews = [cell.contentView subviews];
UILabel *nameLabel = [subviews objectAtIndex:0];
UILabel *abbrevLabel = [subviews objectAtIndex:1];
UILabel *idLabel = [subviews objectAtIndex:2];
// NSLog(#"6 - Countries in Region %#", countriesInRegion);
if (isFiltered == NO)
{
nameLabel.text = [countryInfo objectForKey:#"countryName"];
abbrevLabel.text = [countryInfo objectForKey:#"countryAbbrev"];
idLabel.text = [countryInfo objectForKey:#"countryID"];
// NSLog(#"5 - Our list of countries: %#", nameLabel.text);
// NSLog(#"Country Info %#",countryInfo);
}
else
{
nameLabel.text = [filteredCountries objectAtIndex:2];
abbrevLabel.text = [filteredCountries objectAtIndex:1];
idLabel.text = [filteredCountries objectAtIndex:0];
NSLog(#"4 - Here are your results: %#", filteredCountries);
}
return cell;
}
#pragma mark - UISearchBarDelegate Methods
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if (searchText.length == 0) {
isFiltered = NO;
}
else
{
isFiltered = YES;
NSLog(#"You entered %#", searchText);
filteredCountries = [[NSMutableArray alloc] init];
countryKeys = [dict1 allKeys];
NSLog(#"countryKeys %#", countryKeys);
for (int i = 0; i < countryKeys.count; i++) {
countryKey = [countryKeys objectAtIndex:i];
NSLog(#"country key is %#", countryKey);
{
NSRange countryNameRange = [countryKey rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (countryNameRange.location !=NSNotFound)
{
[filteredCountries addObject:countryKey];
NSLog(#"Filtered Countries %#", filteredCountries);
}
}
}
}
[dictTableView reloadData];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[mySearchBar resignFirstResponder];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#end
That error simply means that you are exceeding the bound of an array.
Specifically at a first sight, I think you got wrong the number of sections and that it doesn't match the number of elements in your array.
I noticed that when filtered is equal to YES you are returning filteredCountries.count for both number of rows and number of sections.
It doesn't look right and I think you should double check you indexes.

CoreData - could not locate an NSManagedObjectModel

I'm getting the error below, I don't know what I'm doing wrong.
I guess there is the managedobject which cannot be located, but... arf !
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'Boxes''
here is my .m ( only the two main functions )
- (void)loadCoreData
{
[[NSNotificationCenter defaultCenter] postNotificationName:#"Test" object:self];
context = [app managedObjectContext];
NSError *err;
// GET THE JSON
NSString *urlString = [NSString stringWithFormat:#"http://localhost:8888/json.txt"];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
NSMutableArray *json = (NSMutableArray* )[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err];
// FILL THE ENTITY
for (int i = 0; i != 7; i++)
{
Boxes *boxes = [NSEntityDescription insertNewObjectForEntityForName:#"Boxes" inManagedObjectContext:context];
boxes.name = [[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"name"] ;
boxes.sexe = [[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"sexe"] ;
boxes.topic = [[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"topic"] ;
boxes.number = [NSNumber numberWithInt:[[[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"number"] intValue]];
}
request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Boxes" inManagedObjectContext:context];
[request setEntity:entity];
arrayForPredicate = [context executeFetchRequest:request error:&err];
}
- (void) fillSexArray:(NSString *)sexe
{
// PREDICATE TO GET AN ARRAY OF PRODUCT WITH SEXE EQUAL TO
NSPredicate *sex;
if ([sexe isEqualToString:#"both"])
{
sex = [NSPredicate predicateWithFormat:#"sexe = %# OR sexe = %#", #"female", #"male"];
}
else
{
sex = [NSPredicate predicateWithFormat:#"sexe = %#", sexe];
}
NSArray *BoxWithSex = [arrayForPredicate filteredArrayUsingPredicate:sex];
NSMutableArray *mutableArray = [self createMutableArray:BoxWithSex];
// NSLog(#"%#", [[mutableArray objectAtIndex:1] valueForKey:#"name"]);
// NSUInteger numObjects = [mutableArray count];
}
my .h :
#interface AddViewController : UIViewController
{
IBOutlet UIButton *male;
IBOutlet UIButton *female;
IBOutlet UIButton *couple;
UIButton *maleBtn;
BOOL flag;
NSArray *arrayForPredicate;
NSFetchedResultsController *fetchedResultsController;
NSManagedObjectContext *context;
NSFetchRequest *request;
}
#property (nonatomic, retain) WonderAppDelegate *app;
- (void) fillSexArray:(NSString *)sexe;
- (NSMutableArray *)createMutableArray:(NSArray *)array;
- (void)loadCoreData;
- (void)sexeButtonPressed;
- (void)sexeArray;
#end
EDIT creating the managedObject :
+ (id)boxWithDictionary:(NSDictionary *)dict withManagedObjectContext:(NSManagedObjectContext *)managedObjectContext;
{
Boxes *boxes = [NSEntityDescription insertNewObjectForEntityForName:#"Boxes"
inManagedObjectContext:managedObjectContext];
boxes.name = [dict objectForKey:#"name"];
boxes.sexe = [dict objectForKey:#"sexe"];
boxes.topic = [dict objectForKey:#"topic"];
boxes.number = [dict objectForKey:#"number"];
return boxes;
}
This is my .m and it is working like that but i don't want the code of the function Add there i want it on loadCoreData.
//
// AddViewController.m
// CoreDataTuto
//
// Created by Clement Yerochewski on 30/04/12.
// Copyright (c) 2012 Weblib. All rights reserved.
//
#import "AddViewController.h"
#import "Boxes.h"
#implementation AddViewController
#synthesize app, context;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 768, 44)];
UINavigationItem *navItem = [[UINavigationItem alloc] initWithTitle:#"Add Detail"];
[navBar pushNavigationItem:navItem animated:NO];
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:#"Cancel" style:UIBarButtonItemStylePlain target:self action:#selector(cancel)];
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:#"Add" style:UIBarButtonItemStyleBordered target:self action:#selector(add)];
navItem.leftBarButtonItem = cancelButton;
navItem.rightBarButtonItem = addButton;
[self.view addSubview:navBar];
app = [[UIApplication sharedApplication] delegate];
}
return self;
}
- (void) add{
[self dismissModalViewControllerAnimated:YES];
// PREDICATE TO GET AN ARRAY OF PRODUCT WITH A LENGTH NAME <= 5
// NSPredicate *length;
// length = [NSPredicate predicateWithFormat:#"name.length <= 5"];
// NSArray *BoxWithCheapPrice = [array filteredArrayUsingPredicate:length];
// NSLog(#"Box %#", BoxWithCheapPrice);
// PREDICATE TO GET AN ARRAY OF PRODUCT WITH PRICE BETWEEN $MIN AND $MAX
// NSNumber *min = [NSNumber numberWithInteger:30];
// NSNumber *max = [NSNumber numberWithInteger:100];
// NSPredicate *between;
// between = [NSPredicate predicateWithFormat:#"number BETWEEN %#", [NSArray arrayWithObjects:min, max, nil]];
// NSArray *BoxWithPriceBetween = [array filteredArrayUsingPredicate:between];
// NSLog(#"Box %#", BoxWithPriceBetween);
// NSLog(#"%#", [BoxWithPriceBetween valueForKey:#"name"]);
}
- (NSMutableArray *)createMutableArray:(NSArray *)array
{
return [NSMutableArray arrayWithArray:array];
}
- (IBAction) sexeChoosen: (id) sender
{
switch ( ((UIButton*)sender).tag ){
case 0:
[self fillSexArray:#"male"];
break;
case 1:
[self fillSexArray:#"female"];
break;
default:
[self fillSexArray:#"both"];
}
[self sexeButtonPressed];
}
- (void)sexeButtonPressed
{
if (flag)
{
UIImage * maleImg2 = [UIImage imageNamed:#"pressed.png"];
[maleBtn setImage:maleImg2 forState:UIControlStateNormal];
flag = NO;
[self sexeArray];
}
else
{
UIImage * maleImg1 = [UIImage imageNamed:#"unpressed.png"];
[maleBtn setImage:maleImg1 forState:UIControlStateNormal];
flag = YES;
[self sexeArray];
}
}
- (void)sexeArray
{
}
- (void)loadCoreData
{
}
- (void) fillSexArray:(NSString *)sexe
{
context = [app managedObjectContext];
// GET THE JSON
NSString *urlString = [NSString stringWithFormat:#"http://localhost:8888/json.txt"];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
NSError *err;
NSMutableArray *json = (NSMutableArray* )[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err];
// FILL THE ENTITY
for (int i = 0; i != 7; i++)
{
Boxes *boxes = [NSEntityDescription insertNewObjectForEntityForName:#"Boxes" inManagedObjectContext:context];
boxes.name = [[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"name"] ;
boxes.sexe = [[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"sexe"] ;
boxes.topic = [[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"topic"] ;
boxes.number = [NSNumber numberWithInt:[[[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"number"] intValue]];
}
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Boxes" inManagedObjectContext:context];
[request setEntity:entity];
arrayForPredicate = [context executeFetchRequest:request error:&err];
NSPredicate *sex;
// PREDICATE TO GET AN ARRAY OF PRODUCT WITH SEXE EQUAL TO
if ([sexe isEqualToString:#"both"])
{
sex = [NSPredicate predicateWithFormat:#"sexe = %# OR sexe = %#", #"female", #"male"];
}
else
{
sex = [NSPredicate predicateWithFormat:#"sexe = %#", sexe];
}
NSArray *BoxWithSex = [arrayForPredicate filteredArrayUsingPredicate:sex];
NSMutableArray *mutableArray = [self createMutableArray:BoxWithSex];
NSLog(#"SEXE CHOOSEN %#", mutableArray);
// NSLog(#"%#", [[mutableArray objectAtIndex:1] valueForKey:#"name"]);
NSUInteger numObjects = [mutableArray count];
NSLog(#"%d", numObjects);
}
- (void) cancel{
[self dismissModalViewControllerAnimated:YES];
}
- (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
{
flag = YES;
maleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
maleBtn.frame = CGRectMake(40, 47, 107, 75);
[maleBtn setTitle:#"male" forState:UIControlStateNormal];
UIImage * maleImg1 = [UIImage imageNamed:#"unpressed.png"];
[maleBtn setImage:maleImg1 forState:UIControlStateNormal];
[maleBtn addTarget:self action:#selector(sexeChoosen:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:maleBtn];
[self loadCoreData];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)viewDidUnload
{
[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 (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
Have you updated your model after creating the persistent store? Try to delete your app from the simulator (or the database file) and run it again..

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.

Getting a crash relating to deallocated instance

I am getting a crash at line [selectedSession release]; in dealloc:
Default [NSCheapMutableString release]: message sent to deallocated instance
I don't understand why isn't this normal to put in dealloc?
All current code below:
LogViewController
#implementation LogViewController
#synthesize fetchedResultsController = __fetchedResultsController;
#synthesize managedObjectContext;
#synthesize logArray;
#synthesize logTableView;
#synthesize imageView;
#synthesize session;
#synthesize selectedSession;
- (void)dealloc
{
[logArray release];
[logTableView release];
[session release];
[__fetchedResultsController release];
[managedObjectContext release];
[imageView release];
[selectedSession release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
self.logTableView.rowHeight = 47;
[super viewDidLoad];
self.navigationItem.title = #"Log";
logTableView.backgroundColor = [UIColor clearColor];
logTableView.separatorColor = [UIColor grayColor];
self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:24/255.0 green:83/255.0 blue:170/255.0 alpha:1.0];
self.logArray = [[NSArray alloc]initWithObjects:#"Today", #"Previous", #"Past Week", #"Past Month", #"All Workouts", nil];
if (managedObjectContext == nil)
{
self.managedObjectContext = [(CurlAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
}
}
- (void)viewDidUnload
{
self.logTableView = nil;
self.fetchedResultsController = nil;
self.imageView = nil;
self.managedObjectContext = nil;
[super viewDidUnload];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.logArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
TDBadgedCell *cell = [[[TDBadgedCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (void)configureCell:(TDBadgedCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
cell.textLabel.textColor = [UIColor blackColor];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.text = [logArray objectAtIndex:indexPath.row];
cell.backgroundColor = [UIColor clearColor];
cell.imageView.image = [UIImage imageNamed:#"17-bar-chart.png"];
UIImageView *myImageView = nil;
myImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"silvercell5.png"]];
[cell setBackgroundView:myImageView];
[myImageView release];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMM d, y"];
NSDate *date = nil;
if (indexPath.row == 0)
{
date = [NSDate date];
NSString *dateString = [dateFormatter stringFromDate:date];
cell.badgeString = dateString;
}
else if (indexPath.row == 1)
{
if ([[self.fetchedResultsController fetchedObjects]count] > 1)
{
self.session = [[self.fetchedResultsController fetchedObjects]objectAtIndex:1];
NSDate *date = self.session.timeStamp;
NSString *dateString = [dateFormatter stringFromDate:date];
cell.badgeString = dateString;
}
else
{
cell.badgeString = #"None";
}
}
else if (indexPath.row > 1)
{
cell.badgeString = [NSString stringWithFormat:#"%i", [[self.fetchedResultsController fetchedObjects]count]];
}
cell.badgeColor = [UIColor colorWithRed:24/255.0 green:83/255.0 blue:170/255.0 alpha:1.0];
[dateFormatter release];
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if (indexPath.row == 0 || indexPath.row == 1)
{
SessionViewController *detailViewController = [[SessionViewController alloc] initWithNibName:#"SessionViewController" bundle:nil];
detailViewController.title = [logArray objectAtIndex: indexPath.row];
self.selectedSession = (Session *)[__fetchedResultsController objectAtIndexPath:indexPath];
detailViewController.selectedSession = self.selectedSession;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMM d, y"];
NSString *dateString = [dateFormatter stringFromDate:selectedSession.timeStamp];
detailViewController.title = dateString;
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
[dateFormatter release];
}
else
{
LogResultsViewController *detailViewController = [[LogResultsViewController alloc] initWithNibName:#"LogResultsTableViewController" bundle:nil];
detailViewController.title = [logArray objectAtIndex: indexPath.row];
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
}
}
#pragma mark - Fetched results controller
- (NSFetchedResultsController *)fetchedResultsController
{
if (fetchedResultsController != nil)
{
return fetchedResultsController;
}
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Session" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0] ;
NSDate *today = [NSDate date];
NSDate *thisWeek = [today dateByAddingTimeInterval: -604800.0];
NSDate *thisMonth = [today dateByAddingTimeInterval: -2629743.83]; // Use NSCalendar for
if (indexPath.row ==2)
{
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"(date >= %#) AND (date <= %#)", thisWeek, today]];
}
else if (indexPath.row ==3)
{
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"(date >= %#) AND (date <= %#)", thisMonth, today]];
}
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"timeStamp" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error])
{
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
NSLog(#"Number of Objects = %i",
[[fetchedResultsController fetchedObjects] count]);
return fetchedResultsController;
NSLog(#"Number of Objects = %i",
[[fetchedResultsController fetchedObjects] count]);
}
#pragma mark - Fetched results controller delegate
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[self.logTableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
switch(type)
{
case NSFetchedResultsChangeInsert:
[self.logTableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.logTableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
UITableView *tableView = self.logTableView;
switch(type)
{
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
[self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
break;
case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[self.logTableView endUpdates];
}
LogResultsViewController
#implementation LogResultsViewController
#synthesize fetchedResultsController = __fetchedResultsController;
#synthesize managedObjectContext;
#synthesize resultsTableView;
#synthesize selectedSession;
- (void)dealloc
{
[__fetchedResultsController release];
[managedObjectContext release];
[selectedSession release];
[resultsTableView release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.resultsTableView.separatorColor = [UIColor grayColor];
self.resultsTableView.rowHeight = 50;
[self managedObjectContext];
}
- (NSManagedObjectContext *)managedObjectContext
{
if (managedObjectContext != nil)
{
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [(CurlAppDelegate *)[[UIApplication sharedApplication] delegate] persistentStoreCoordinator];
if (coordinator != nil)
{
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return managedObjectContext;
}
- (void)viewDidUnload
{
[super viewDidUnload];
self.managedObjectContext = nil;
self.fetchedResultsController = nil;
self.resultsTableView = nil;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
- (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];
}
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
Session *session = (Session *)[__fetchedResultsController objectAtIndexPath:indexPath];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"eeee, MMM d, y"];
NSString *dateString = [dateFormatter stringFromDate:session.timeStamp];
NSDate *lastDate = session.timeStamp;
NSDate *todaysDate = [NSDate date];
NSTimeInterval lastDiff = [lastDate timeIntervalSinceNow];
NSTimeInterval todaysDiff = [todaysDate timeIntervalSinceNow];
NSTimeInterval dateDiff = todaysDiff-lastDiff;
NSTimeInterval dayDifference = dateDiff/86400;
int days = (int) dayDifference;
NSLog(#"%i days",days);
cell.textLabel.text = dateString;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.detailTextLabel.text = [NSString stringWithFormat: #"%i days ago", days];
cell.detailTextLabel.textColor = [UIColor colorWithRed:24/255.0 green:83/255.0 blue:170/255.0 alpha:1.0];
cell.imageView.image = [UIImage imageNamed:#"11-clock.png"];
self.resultsTableView.tableFooterView = [[[UIView alloc] init] autorelease];
UIImageView *myImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"silvercell3.png"]];
[cell setBackgroundView:myImageView];
[dateFormatter release];
[myImageView release];
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
// Delete the managed object for the given index path
NSManagedObjectContext *context = [__fetchedResultsController managedObjectContext];
[context deleteObject:[__fetchedResultsController objectAtIndexPath:indexPath]];
// Commit the change.
NSError *error = nil;
// Update the array and table view.
if (![managedObjectContext save:&error])
{
// Handle the error.
}
//[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
}
}
// 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;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
SessionViewController *sessionViewController = [[SessionViewController alloc] initWithNibName:#"SessionViewController" bundle:nil];
selectedSession = (Session *)[__fetchedResultsController objectAtIndexPath:indexPath];
sessionViewController.selectedSession = self.selectedSession;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMM d, y"];
NSString *dateString = [dateFormatter stringFromDate:selectedSession.timeStamp];
sessionViewController.title = dateString;
[self.navigationController pushViewController:sessionViewController animated:YES];
[sessionViewController release];
[dateFormatter release];
}
#pragma mark - Fetched results controller
- (NSFetchedResultsController *)fetchedResultsController
{
if (fetchedResultsController != nil)
{
return fetchedResultsController;
}
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Session" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"timeStamp" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
NSError *error = nil;
if (![fetchedResultsController performFetch:&error])
{
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return fetchedResultsController;
}
#pragma mark - Fetched results controller delegate
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[self.resultsTableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
switch(type)
{
case NSFetchedResultsChangeInsert:
[self.resultsTableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.resultsTableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
UITableView *tableView = self.resultsTableView;
switch(type)
{
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
[self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
break;
case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[self.resultsTableView endUpdates];
}
SessionViewController
#implementation SessionViewController
#synthesize exerciseArray;
#synthesize selectedSession;
- (void)dealloc
{
[exerciseArray release];
[selectedSession release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(IBAction)showActionSheet {
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:#"Share" delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil otherButtonTitles:#"Twitter",#"Facebook",nil];
[actionSheet showInView:self.tabBarController.view];
[actionSheet release];
}
- (void)tweet
{
SHKItem *aTweet = [SHKItem text:[NSString stringWithFormat: #"Twitter: testing 1,2,3."]];
[SHKTwitter shareItem:aTweet];
}
- (void)facebook
{
SHKItem *post = [SHKItem text: [NSString stringWithFormat: #"Facebook: testing 1,2,3."]];
// post.URL = [NSURL URLWithString:#"http://sugarrush-app.com/"];
[SHKFacebook shareItem:post];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
UIBarButtonItem *actionButton = [[UIBarButtonItem alloc] initWithTitle:#"Share" style:UIBarButtonItemStylePlain target:self action:#selector(showActionSheet)];
self.navigationItem.rightBarButtonItem = actionButton;
[actionButton release];
NSSet *exercises = [self.selectedSession valueForKey:#"exercises"];
NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"timeStamp" ascending:YES]];
NSArray *sorted = [exercises sortedArrayUsingDescriptors:sortDescriptors];
self.exerciseArray = sorted;
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [exerciseArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
Exercise *exercise = (Exercise *)[exerciseArray objectAtIndex:indexPath.row];
cell.textLabel.text = exercise.name;
return cell;
}
#end
The only objects you should be releasing or setting to nil in viewDidUnload are like buttons, labels, textBoxes etc.
When you do self.selectedSession = nil, for example, it is calling the release for that method; that is the point of properties, they handle the allocs and releases.
You posted a tableView:didSelectRowAtIndexPath:, but I don't think you told us which class that was in.
In any case, that method seems to have a bug:
selectedSession = (Session *)[__fetchedResultsController objectAtIndexPath:indexPath];
sessionViewController.selectedSession = self.selectedSession;
I think on the first line, you meant to say self.selectedSession, assuming you go on to release selectedSession in this class' dealloc. (This may not be your only issue)
EDIT:
You should set properties to nil in viewDidUnload if and only if those properties were set as a result of the loading of the view from your nib, or were set in loadView, or in viewDidLoad. The reason you're doing this is because viewDidLoad or loadView may be called more than once during the lifetime of the view controller.
EDIT:
Check that you are using the property when setting fetchedResultsController and make sure you aren't setting that to nil on viewDidUnload.
Dont set selectedSession and exerciseArray to nil in viewDidUnload.
Since you're doing that, it will crash in the dealloc as you're trying to release nil objects.
Also, before you release arrays, it's always a good idea to call [array removeAllObjects].
in your viewDidLoad method you are setting self.selectedSession and self.exerciseArray to nil. You should only set interface outlets to nil in viewDidLoad. But this isn't the cause of your crash because by the time you get to dealloc, you are just sending release to nil.
you might want to look into the contents of the selectedSession Object. you might be over releasing an NSString in one of it's members