prepareforSegue tableViewCell to different detailTableViews - iphone

I´m having a tableView in a viewController with an array (3 labelTitles to 3 different detailViews). My problem is in the prepareForSegue-method, I dont really know how to call the detailViews. I use the correct segue identifiers names.
"master".m:
#import "GuideTableViewController.h"
#import "GuideDetailTableViewController.h"
#import "GuideDetailTableViewController2.h"
#import "GuideDetailTableViewController3.h"
#import <QuartzCore/QuartzCore.h>
#import "customImageCell.h"
#interface GuideTableViewController (){
NSMutableData *weatherResponseData;
NSArray *titleLabels;
NSArray *imagesLeft;
}
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#property (weak, nonatomic) IBOutlet UIImageView *imgHeader;
#property (weak, nonatomic) IBOutlet UIImageView *ImgTitle;
#property (weak, nonatomic) IBOutlet UIImageView *ImgWeather;
#property (weak, nonatomic) IBOutlet UIButton *btnMap;
#property (weak, nonatomic) IBOutlet UILabel *LabelWeather;
#property (weak, nonatomic) IBOutlet UILabel *LabelWeather2;
#end
#implementation GuideTableViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
//Weather method
- (void) loadWeather{
NSURLRequest *theRequest = [NSURLRequest requestWithURL:
[NSURL URLWithString:#"http://api.wunderground.com/api/3919480da5014c98/conditions/q/BR/Sao_Sebastiao.json"]];
NSURLConnection *theConnection=[[NSURLConnection alloc]
initWithRequest:theRequest delegate:self];
if(theConnection){
weatherResponseData = [[NSMutableData alloc] init];
} else {
NSLog(#"failed");
}
}
//Delegates for WeatherData
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[weatherResponseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[weatherResponseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSString *msg = [NSString stringWithFormat:#"Failed: %#", [error description]];
NSLog(#"%#",msg);
}
//All the data was loaded, let's see what we've got...
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:weatherResponseData options:NSJSONReadingMutableLeaves error:&myError];
NSArray *results = [res objectForKey:#"current_observation"];
NSString *cur = [results valueForKey:#"weather"];
NSString *tmp = [results valueForKey:#"temperature_string"];
NSString *wind = [results valueForKey:#"wind_string"];
NSLog(#"Current conditions: %#, %#º, %#", cur, tmp, wind);
self.LabelWeather.text = cur;
self.LabelWeather2.text = tmp;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[self loadWeather];
titleLabels = [NSArray arrayWithObjects:#"Where to stay",#"Where to eat",#"What to do",nil];
imagesLeft = [NSArray arrayWithObjects:#"btn_Stay.png", #"btn_Eat.png", #"btn_Todo.png", nil];
//set background
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"background.jpg"]];
//rounded corners
[self.tableView.layer setCornerRadius:9.0];
[self.ImgWeather.layer setCornerRadius:9.0];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//TableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return titleLabels.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
customImageCell *cell = (customImageCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSString *cellLabel = [titleLabels objectAtIndex:indexPath.row];
cell.titleLabel.text = cellLabel;
NSString *cellImage = [imagesLeft objectAtIndex:indexPath.row];
UIImage *cellIcon = [UIImage imageNamed:cellImage];
cell.imageLeft.image = cellIcon;
return cell;
}
//To detailTableViewController
- (void)tableView:(UITableView *)tableView didselectRowAtIndexPath:(NSIndexPath *)indexPath{
if(indexPath.row == 0){
[self performSegueWithIdentifier:#"stay" sender:self];
}else if(indexPath.row ==1 ){
[self performSegueWithIdentifier:#"eat" sender:self];
}else{
[self performSegueWithIdentifier:#"todo" sender:self];
}
}
- (void) viewWillAppear:(BOOL)animated{
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.tableView.indexPathForSelectedRow];
[cell setSelected:NO];
//Hide navbar
[self.navigationController setNavigationBarHidden:YES];
}
//Show navbar in detailView
-(void)viewWillDisappear:(BOOL)animated{
[self.navigationController setNavigationBarHidden:NO];
}
#end

change didselectRow
- (void)tableView:(UITableView *)tableView didselectRowAtIndexPath:(NSIndexPath *)indexPath{
if(indexPath.row == 0){
[self performSegueWithIdentifier:#"stay" sender:self];
}else if(indexPath.row ==1 ){
[self performSegueWithIdentifier:#"eat" sender:self];
}else{
[self performSegueWithIdentifier:#"todo" sender:self];
}
}

Related

DidSelectRowAtIndexPath not being called

I have 3 different detailTableViews that my cells in my masterTableView will call when touched.
Please see my master.m file:
#import "GuideTableViewController.h"
#import "GuideDetailTableViewController.h"
#import "GuideDetailTableViewController2.h"
#import "GuideDetailTableViewController3.h"
#import <QuartzCore/QuartzCore.h>
#interface GuideTableViewController (){
NSMutableData *weatherResponseData;
NSArray *headGuide;
NSArray *leftImages;
}
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#property (weak, nonatomic) IBOutlet UIImageView *imgHeader;
#property (weak, nonatomic) IBOutlet UIImageView *ImgTitle;
#property (weak, nonatomic) IBOutlet UIImageView *ImgWeather;
#property (weak, nonatomic) IBOutlet UIButton *btnMap;
#property (weak, nonatomic) IBOutlet UILabel *LabelWeather;
#property (weak, nonatomic) IBOutlet UILabel *LabelWeather2;
#end
#implementation GuideTableViewController
//Weather method
- (void) loadWeather{
NSURLRequest *theRequest = [NSURLRequest requestWithURL:
[NSURL URLWithString:#"http://api.wunderground.com/api/3919480da5014c98/conditions/q/BR/Sao_Sebastiao .json"]];
NSURLConnection *theConnection=[[NSURLConnection alloc]
initWithRequest:theRequest delegate:self];
if(theConnection){
weatherResponseData = [[NSMutableData alloc] init];
} else {
NSLog(#"failed");
}
}
//Delegates for WeatherData
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[weatherResponseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[weatherResponseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSString *msg = [NSString stringWithFormat:#"Failed: %#", [error description]];
NSLog(#"%#",msg);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:weatherResponseData options:NSJSONReadingMutableLeaves error:&myError];
NSArray *results = [res objectForKey:#"current_observation"];
NSString *cur = [results valueForKey:#"weather"];
NSString *tmp = [results valueForKey:#"temperature_string"];
NSString *wind = [results valueForKey:#"wind_string"];
NSLog(#"Current conditions: %#, %#º, %#", cur, tmp, wind);
self.LabelWeather.text = cur;
self.LabelWeather2.text = tmp;
}
//JSONmethod
- (void) loadJSON{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//code
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://dl.dropbox.com/u/100670549/guide.json"]];
NSError *error;
if (data)
{
headGuide = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
for (NSDictionary *dictionary in headGuide){
// NSLog([dictionary description]);
}
}else
{
NSLog(#"Could not load data");
}
dispatch_sync(dispatch_get_main_queue(), ^{
// code
[self.tableView reloadData];
});
});
}
//Load
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[self loadJSON];
[self loadWeather];
leftImages = [NSArray arrayWithObjects:#"btn_Stay.png", #"btn_Eat.png", #"btn_Todo.png", nil];
// set background
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"background.jpg"]];
// rounded corners
[self.tableView.layer setCornerRadius:9.0];
[self.ImgWeather.layer setCornerRadius:9.0];
}
#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 headGuide.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
NSArray *dict = [headGuide objectAtIndex:indexPath.row];
cell.textLabel.text = [dict valueForKey:#"title"];
NSString *cellImage = [leftImages objectAtIndex:indexPath.row];
UIImage *cellIcon = [UIImage imageNamed:cellImage];
cell.imageView.image = cellIcon;
return cell;
}
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:#"whereStay"]){
GuideDetailTableViewController *vc = [segue destinationViewController];
NSIndexPath *index = sender;
NSDictionary *dict = [headGuide objectAtIndex:index.row];
vc.stayGuide = dict;
}
else if ([segue.identifier isEqualToString:#"whereEat"]){
GuideDetailTableViewController2 *vc1 = [segue destinationViewController];
NSIndexPath *index = sender;
NSDictionary *dict = [headGuide objectAtIndex:index.row];
vc1.eatGuide = dict;
}
else if ([segue.identifier isEqualToString:#"whatTodo"]){
GuideDetailTableViewController3 *vc2 = [segue destinationViewController];
NSIndexPath *index = sender;
NSDictionary *dict = [headGuide objectAtIndex:index.row];
vc2.todoGuide = dict;
}
}
#pragma mark - tableView delegate
- (void)tableView:(UITableView *)tableView didselectRowAtIndexPath:(NSIndexPath *)indexPath{
if(indexPath.row == 0){
[self performSegueWithIdentifier:#"whereStay" sender:indexPath];
}else if(indexPath.row ==1 ){
[self performSegueWithIdentifier:#"whereEat" sender:indexPath];
}else{
[self performSegueWithIdentifier:#"whatTodo" sender:indexPath];
}
[tableView setAllowsSelection:YES];
}
#end
Your method signature is also not properly capitalized:
- (void)tableView:(UITableView *)tableView didselectRowAtIndexPath:(NSIndexPath *)indexPath{
should be
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
Method names are case sensitive.
Additionally, make sure you're setting the tableView's delegate with
self.tableView.delegate = self;
It doesn't look like you're setting this object as the delegate of your table view. In your -viewDidLoad method, you should call [[self tableView] setDelegate:self];
Where is your protocol for tableview delegate and datasource?
#interface GuideTableViewController : UIViewController <UITableViewDataSource,UITableViewDelegate>
{
//Attributes...
IBOutlet UITableView *tableView;
}
in viewDidLoad, you should set the delegates:
tableView.delegate = self;
tableView.dataSource = self;
you could also set delegates in xib files...
So your delegates Methods should works... Check out with apple docs about tableview:
http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableView_Class/Reference/Reference.html

TableView to detailTableView - one step behind

When I connect the my tableView to a detailtableView I get the the "error" that the detailtableView is one step behind. For example when clicking the 2nd cell in the mastertableView it show the 1st cell detailInformation. Hope you understand my problem.
See my .m.
#import "GuideTableViewController.h"
#import "GuideDetailTableViewController.h"
#interface GuideTableViewController (){
NSArray *guide;
}
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#end
#implementation GuideTableViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
//JSONmetod
- (void) loadJSON{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//code
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://dl.dropbox.com/u/100670549/test.json"]];
NSError *error;
if (data)
{
guide = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
for (NSDictionary *dictionary in guide){
NSLog([dictionary description]);
}
}else
{
NSLog(#"Could not load data");
}
dispatch_sync(dispatch_get_main_queue(), ^{
// code
[self.tableView reloadData];
});
});
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
//Anropa json
[self loadJSON];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//TableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return guide.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
NSDictionary *dict = [guide objectAtIndex:indexPath.row];
cell.textLabel.text = [dict valueForKey:#"title"];
return cell;
}
//Till detailView
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:#"showStay"]){
GuideDetailTableViewController *tvc = [segue destinationViewController];
NSIndexPath *index = sender;
NSDictionary *dict = [guide objectAtIndex:index.row];
tvc.stay = dict;
}
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
[self performSegueWithIdentifier:#"showStay" sender:indexPath];
}
#end
Thanks in advance!
you used didDeselectRowAtIndexPath instead of didSelectRowAtIndexPath Delegate method, common autocomplete mistake.

Implement MWFeedParser in a ViewController

I'm trying to use the MWFeedParser library in my app. On my homescreen, I have a view controller named NewsViewController.
In the MWFeedParser library, the root view controller is called RootViewController. I've tried to copy all the code from the RootViewController into the NewsViewController .H + .M and in IB I've linked the tableview to "dataSource" and "delegate". But when my app starts the tableview is empty.
Here's how to code looks like:
.H:
#import <UIKit/UIKit.h>
#import "MWFeedItem.h"
#import "MWFeedParser.h"
#interface NewsViewController : UITableViewController <MWFeedParserDelegate, UITableViewDelegate, UITableViewDataSource> {
// Parsing
MWFeedParser *feedParser;
NSMutableArray *parsedItems;
// Displaying
NSArray *itemsToDisplay;
NSDateFormatter *formatter;
IBOutlet UITableView *tableView;
}
// Properties
#property (nonatomic, retain) NSArray *itemsToDisplay;
#property (nonatomic, retain) IBOutlet UITableView *tableView;
-(IBAction)goHome;
#end
.M:
#import "NSString+HTML.h"
#import "MWFeedParser.h"
#import "DetailTableViewController.h"
#implementation NewsViewController
#synthesize itemsToDisplay, tableView;
#pragma mark -
#pragma mark View lifecycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"News", #"News");
self.tabBarItem.image = [UIImage imageNamed:#"icon_news"]; }
return self;
}
- (void)viewDidLoad
{
label.shadowOffset = CGSizeMake(0.0f, 1.0f);
label.textColor = [UIColor colorWithRed:0xB3/249.0 green:0xB3/252.0 blue:0xB3/253.0 alpha:1];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
// Date
// Setup
formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterShortStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
parsedItems = [[NSMutableArray alloc] init];
self.itemsToDisplay = [NSArray array];
// Refresh button
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self
action:#selector(refresh)];
// Parse
NSURL *feedURL = [NSURL URLWithString:#"http://www.mywebsite.com/feed/"];
feedParser = [[MWFeedParser alloc] initWithFeedURL:feedURL];
feedParser.delegate = self;
feedParser.feedParseType = ParseTypeFull; // Parse feed info and all items
feedParser.connectionType = ConnectionTypeAsynchronously;
[feedParser parse];
UIImage *someImage = [UIImage imageNamed:#"back_active1#2x.png"];
[button setBackgroundImage:someImage forState:UIControlStateHighlighted];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewDidAppear:(BOOL)animated {
static BOOL first = YES;
if (first) {
UIViewController *popup = [[Home1ViewController alloc] initWithNibName:#"Home1ViewController" bundle:nil];
[self presentViewController:popup animated:NO completion:nil];
first = NO;
}
}
#pragma mark -
#pragma mark Parsing
// Reset and reparse
- (void)refresh {
self.title = #"Refreshing...";
[parsedItems removeAllObjects];
[feedParser stopParsing];
[feedParser parse];
self.tableView.userInteractionEnabled = NO;
self.tableView.alpha = 0.3;
}
- (void)updateTableWithParsedItems {
self.itemsToDisplay = [parsedItems sortedArrayUsingDescriptors:
[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:#"date"
ascending:NO]]];
self.tableView.userInteractionEnabled = YES;
self.tableView.alpha = 1;
[self.tableView reloadData];
}
#pragma mark -
#pragma mark MWFeedParserDelegate
- (void)feedParserDidStart:(MWFeedParser *)parser {
NSLog(#"Started Parsing: %#", parser.url);
}
- (void)feedParser:(MWFeedParser *)parser didParseFeedInfo:(MWFeedInfo *)info {
NSLog(#"Parsed Feed Info: “%#”", info.title);
self.title = info.title;
}
- (void)feedParser:(MWFeedParser *)parser didParseFeedItem:(MWFeedItem *)item {
NSLog(#"Parsed Feed Item: “%#”", item.title);
if (item) [parsedItems addObject:item];
}
- (void)feedParserDidFinish:(MWFeedParser *)parser {
NSLog(#"Finished Parsing%#", (parser.stopped ? #" (Stopped)" : #""));
[self updateTableWithParsedItems];
}
- (void)feedParser:(MWFeedParser *)parser didFailWithError:(NSError *)error {
NSLog(#"Finished Parsing With Error: %#", error);
if (parsedItems.count == 0) {
self.title = #"Failed"; // Show failed message in title
} else {
// Failed but some items parsed, so show and inform of error
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Parsing Incomplete"
message:#"There was an error during the parsing of this feed. Not all of the feed items could parsed."
delegate:nil
cancelButtonTitle:#"Dismiss"
otherButtonTitles:nil];
[alert show];
}
[self updateTableWithParsedItems];
}
#pragma mark -
#pragma mark Table view data source
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return itemsToDisplay.count;
}
// Customize the appearance of table view cells.
- (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];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Configure the cell.
MWFeedItem *item = [itemsToDisplay objectAtIndex:indexPath.row];
if (item) {
// Process
NSString *itemTitle = item.title ? [item.title stringByConvertingHTMLToPlainText] : #"[No Title]";
NSString *itemSummary = item.summary ? [item.summary stringByConvertingHTMLToPlainText] : #"[No Summary]";
// Set
cell.textLabel.font = [UIFont boldSystemFontOfSize:15];
cell.textLabel.text = itemTitle;
NSMutableString *subtitle = [NSMutableString string];
if (item.date) [subtitle appendFormat:#"%#: ", [formatter stringFromDate:item.date]];
[subtitle appendString:itemSummary];
cell.detailTextLabel.text = subtitle;
}
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Show detail
DetailTableViewController *detail = [[DetailTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
detail.item = (MWFeedItem *)[itemsToDisplay objectAtIndex:indexPath.row];
[self.navigationController pushViewController:detail animated:YES];
// Deselect
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#end
what you do is in feedparserDidFinish method , try to reload table....like below...
- (void)feedParserDidFinish:(MWFeedParser *)parser {
NSLog(#"Finished Parsing%#", (parser.stopped ? #" (Stopped)" : #""));
[self.tableView reloadData];
}
let me know it is working or not!!!!!
Happy Coding!!!!!!!

Why will my plist not populate my UITableView?

I have made some progress and am editing the question to be current again. My big issue now is that the grouped table view will load, but shows all of everything in each section with each row. Also, my UIAlertView is returning all references to my plist (null). How would I fix this because the references to the plist are killing me. Any and all help would be greatly appreciated!
Here is the plain text version of my plist file:
<array>
<dict>
<key>eventName</key>
<string>Comedy Caravan</string>
<key>eventSpecifics</key>
<string>Nicholas Anthony</string>
<key>eventLocation</key>
<string>The Cats Den</string>
<key>eventType</key>
<string>Comedy</string>
<key>eventGoodies</key>
<string>Both</string>
<key>eventDate</key>
<date>2010-07-23T00:00:00Z</date>
</dict>
<dict>
<key>eventName</key>
<string>Comedy Caravan</string>
<key>eventLocation</key>
<string>The Cats Den</string>
<key>eventType</key>
<string>Comedy</string>
<key>eventSpecifics</key>
<string>Bruce Baum</string>
<key>eventGoodies</key>
<string>Prizes</string>
<key>eventDate</key>
<date>2010-07-24T00:00:00Z</date>
</dict>
<dict>
<key>eventName</key>
<string>Late Night Film Series</string>
<key>eventLocation</key>
<string>The Cats Den</string>
<key>eventType</key>
<string>Comedy</string>
<key>eventSpecifics</key>
<string>Avatar</string>
<key>eventGoodies</key>
<string>Food</string>
<key>eventDate</key>
<date>2010-07-24T02:00:00Z</date>
</dict>
</array>
Here is my ThisWeekViewController.h:
#import <UIKit/UIKit.h>
#class Event;
#interface ThisWeekViewController : UITableViewController
{
NSArray *eventNames;
Event *event;
}
#property (nonatomic, retain) NSArray *eventNames;
#property (nonatomic, retain) Event *event;
#end
and Here is my ThisWeekViewController.m:
#import "ThisWeekViewController.h"
#import "Event.h"
#implementation ThisWeekViewController
#synthesize eventNames;
#synthesize event;
- (void)viewDidLoad {
[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:#"Events" ofType:#"plist"];
NSArray *dict = [[NSArray alloc] initWithContentsOfFile:path];
NSArray *namesArray = [dict valueForKey:#"eventName"];
self.eventNames = namesArray;
[dict release];
[self.tableView reloadData];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
self.eventNames = nil;
}
#pragma mark Table View Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [self.eventNames count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSString *key = [NSString stringWithFormat:#"%#", event.eventName];
return key;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.eventNames count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger row = [indexPath row];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
// Set the cell's text to the event name
cell.textLabel.text = event.eventName;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}
- (void)dealloc {
// [thisWeek release];
[event release];
[eventNames release];
[super dealloc];
}
#end
I have also included my Event.h file
#import <Foundation/Foundation.h>
#interface Event : NSObject {
NSString *eventName;
NSString *eventType;
NSDate *eventDate;
NSString *eventLocation;
NSString *eventGoodies;
NSString *eventSpecifics;
}
- (id)initWithDictionary:(NSDictionary *)aDictionary;
#property (nonatomic, retain) NSString *eventName;
#property (nonatomic, retain) NSString *eventType;
#property (nonatomic, retain) NSString *eventLocation;
#property (nonatomic, retain) NSDate *eventDate;
#property (nonatomic, retain) NSString *eventGoodies;
#property (nonatomic, retain) NSString *eventSpecifics;
#end
and my Event.m file
#import "Event.h"
#implementation Event
#synthesize eventName;
#synthesize eventType;
#synthesize eventDate;
#synthesize eventLocation;
#synthesize eventGoodies;
#synthesize eventSpecifics;
- (id)initWithDictionary:(NSDictionary *)aDictionary {
if ([self init]) {
self.eventName = [aDictionary valueForKey:#"eventName"];
self.eventType = [aDictionary valueForKey:#"eventType"];
self.eventDate = [aDictionary valueForKey:#"eventDate"];
self.eventLocation = [aDictionary valueForKey:#"eventLocation"];
self.eventGoodies = [aDictionary valueForKey:#"eventGoodies"];
self.eventSpecifics = [aDictionary valueForKey:#"eventSpecifics"];
}
return self;
}
- (void)dealloc {
[eventName release];
[eventType release];
[eventDate release];
[eventLocation release];
[eventGoodies release];
[eventSpecifics release];
[super dealloc];
}
#end
I would like to be able to place things such as cell.detailTextLabel.text = event.eventSpecifics and just run off of references like that.
If I recall correctly, UITableViewController reloads the table view in -viewWillAppear:. This may very well be called before -viewDidLoad is called. I would recommend that you insert a call to [self.tableView reloadData] at the end of your implementation of -viewDidLoad.
You should also be calling [super viewDidLoad] at the top of your implementation of -viewDidLoad, and similarly for -viewDidUnload.
Also, you don't need to declare your class as conforming to UITableViewDataSource or UITableViewDelegate as your superclass (UITableViewController) already does that for you.

Problems trying to override methods in Objective-C (iPhone)

this my problem i have a class X that inherits UITableViewController class and a class Y that inherits the X class, when i try to override a method in the Y class the method in the X class is invoked... and i can't find references to understand what's happening... can anyone help me?
Thanks in advance!
Code!
mluListBuilder.h
#import <UIKit/UIKit.h>
#interface mluListBuilder : UITableViewController {
NSString *sListTitle;
NSString *sEntityName;
NSArray *aEntityProperties;
NSMutableArray *maListRecords;
NSManagedObjectContext *mocList;
NSFetchRequest *frListRecords;
NSEntityDescription *edListRecords;
NSArray *aOrderByProperties;
NSArray *aToolBarItems;
NSArray *aToolBarItemsActions;
}
#property (nonatomic, retain) NSString *sListTitle;
#property (nonatomic, retain) NSString *sEntityName;
#property (nonatomic, retain) NSArray *aEntityProperties;
#property (nonatomic, retain) NSMutableArray *maListRecords;
#property (nonatomic, retain) NSManagedObjectContext *mocList;
#property (nonatomic, retain) NSFetchRequest *frListRecords;
#property (nonatomic, retain) NSEntityDescription *edListRecords;
#property (nonatomic, retain) NSArray *aOrderByProperties;
#property (nonatomic, retain) NSArray *aToolBarItems;
#property (nonatomic, retain) NSArray *aToolBarItemsActions;
- (id) initWithStyle: (UITableViewStyle) style
listTitle: (NSString *) psListTitle
entityName: (NSString *) psEntityName
entityProperties: (NSArray *) paEntityProperties
orderListByProperties: (NSArray *) paOrderByProperties
toolBarItems: (NSArray *) paToolBarItems
toolBarItemsActions: (NSArray *) paToolBarItemsActions;
- (void)newRecord;
- (void)deleteRecord;
#end
mluListBuilder.m
#import "mluListBuilder.h"
#implementation mluListBuilder
#synthesize sListTitle,
sEntityName,
aEntityProperties,
maListRecords,
mocList,
frListRecords,
edListRecords,
aOrderByProperties,
aToolBarItems,
aToolBarItemsActions;
- (id) initWithStyle: (UITableViewStyle) style
listTitle: (NSString *) psListTitle
entityName: (NSString *) psEntityName
entityProperties: (NSArray *) paEntityProperties
orderListByProperties: (NSArray *) paOrderByProperties
toolBarItems: (NSArray *) paToolBarItems
toolBarItemsActions: (NSArray *) paToolBarItemsActions
{
sListTitle = psListTitle;
sEntityName = psEntityName;
aEntityProperties = paEntityProperties;
aOrderByProperties = paOrderByProperties;
aToolBarItems = paToolBarItems;
aToolBarItemsActions = paToolBarItemsActions;
if (self = [super initWithStyle:style]) {
}
return self;
}
- (void)viewDidLoad {
self.title = NSLocalizedString(sListTitle, nil);
if ([aToolBarItems count] > 0) {
NSMutableArray *maToolBarItems = [[NSMutableArray alloc] init];
self.navigationController.toolbarHidden = NO;
for (int i = 0; i < [aToolBarItems count]; i++) {
UIBarButtonItem * bbiToolBarItem = [[UIBarButtonItem alloc]
initWithTitle:NSLocalizedString([aToolBarItems objectAtIndex:i], nil)
style:UIBarButtonItemStyleBordered
target:self
action:NSSelectorFromString([aToolBarItemsActions objectAtIndex:i])
];
[maToolBarItems addObject:bbiToolBarItem];
}
self.toolbarItems = maToolBarItems;
} else {
self.navigationController.toolbarHidden = YES;
}
if (mocList != nil) {
frListRecords = [[NSFetchRequest alloc] init];
NSSortDescriptor *sdListRecords = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
[frListRecords setSortDescriptors:[[NSArray alloc] initWithObjects:sdListRecords, nil]];
edListRecords = [NSEntityDescription entityForName:sEntityName inManagedObjectContext:mocList];
[frListRecords setEntity:edListRecords];
NSError *errFetchRequest;
maListRecords = [[mocList executeFetchRequest:frListRecords error:&errFetchRequest] mutableCopy];
}
[super viewDidLoad];
}
- (void)viewWillAppear:(BOOL)animated {
NSError *errFetchRequest;
maListRecords = [[mocList executeFetchRequest:frListRecords error:&errFetchRequest] mutableCopy];
[self.tableView reloadData];
if (self.navigationController.toolbarHidden == YES) {
if ([aToolBarItems count] > 0) {
self.navigationController.toolbarHidden = NO;
}
}
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [maListRecords count];
}
// Customize the appearance of table view cells.
- (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];
}
for (UIView *vwExisting in cell.contentView.subviews) {
[vwExisting removeFromSuperview];
}
NSEntityDescription *edCurrentRecord = [maListRecords objectAtIndex:indexPath.row];
UILabel *lblCell = [[UILabel alloc] initWithFrame:CGRectMake(5.0, 5.0, 280, 20.0)];
[lblCell setText:edCurrentRecord.name];
[cell.contentView addSubview:lblCell];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here. Create and push another view controller.
// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:#"AnotherView" bundle:nil];
// [self.navigationController pushViewController:anotherViewController];
// [anotherViewController release];
}
- (void)dealloc {
[super dealloc];
}
- (void)newRecord {
NSLog(#"%#", [self class]);
}
- (void)deleteRecord {
}
#end
mluLawyerCaseSituationsList.h
#import <Foundation/Foundation.h>
#import "mluListBuilder.h";
#interface mluLawyerCaseSituationsList : mluListBuilder {
}
- (void)newRecord;
#end
mluLawyerCaseSituationsList.m
#import "mluLawyerCaseSituationsList.h"
#implementation mluLawyerCaseSituationsList
- (void)newRecord {
NSLog(#"%#", [self class]);
}
#end
Calling the mluLawyerCaseSituationsList
mluLawyerCaseSituationsList *vcCaseSituations = [[mluListBuilder alloc]
initWithStyle:UITableViewStylePlain
listTitle:#"titCaseSituations"
entityName:#"case_situations"
entityProperties:[[NSArray alloc] initWithObjects:#"name", nil]
orderListByProperties:[[NSArray alloc] initWithObjects:#"name", nil]
toolBarItems:[[NSArray alloc] initWithObjects:#"btNew", nil]
toolBarItemsActions:[[NSArray alloc] initWithObjects:#"newRecord", nil]
];
Output... :(
2009-12-17 17:30:02.726 mluLawyer[2862:20b] mluListBuilder
Hope it helps...
I’ve been looking through your code only briefly, but it seems obvious (from code and from the output) that you allocate an instance of class X (mluListBuilder).
Of course, you cannot expect to have a method of class Y (mluLawyerCaseSituationsList), performed when Y is derived from X and the object is of class X.
So, you have:
#interface X : UITableViewController
- (void) method;
#end
#interface Y : X
- (void) method;
#end
You are calling -method, but it is being invoked on X, not Y? Only way that can happen is if you have an instance of X instead of Y (or if someone is playing very silly buggers with the runtime -- unlikely).
Add NSLog(#"%#", [self class]); to the method implementations and see what the class of the instance really is!
You don't give us much information in your question, but the following is how it should work:
Class_X.h:
#interface Class_X : UITableViewController
{
}
- (void)someMethod;
#end
Class_X.m:
#import "Class_X.h"
#implementation Class_X
- (void)someMethod
{
NSLog(#"method in Class_X was called");
}
#end
Class_Y.h:
#import "Class_X.h"
#interface Class_Y : Class_X
{
}
- (void)someMethod;
#end
Class_Y.m:
#import "Class_Y.h"
#implementation Class_Y
- (void)someMethod
{
NSLog(#"method in Class_Y was called");
}
#end
Elsewhere:
#import "Class_Y.h"
...
Class_X * x_instance = [[Class_X alloc] init];
Class_Y * y_instance = [[Class_Y alloc] init];
[x_instance someMethod];
[y_instance someMethod];
[Class_Y release];
[Class_X release];
Output:
method in Class_X was called
method in Class_Y was called