i am unable to display an parsed xml on table view :( - iphone

Please can any one correct my silly mistake as i am unable to show my parsed XML to the Table view.
I want my tag to be displayed on table view.
here is my code (ignore my syntax ... as i am unable to paste it correctly here)....
XML TO BE PARSED
<Table><category><Name>Books</Name><cid>2</cid><Logo>http://litofinter.es.milfoil.arvixe.com/Thumbnail/5.png</Logo><Product><pid>55</pid><Title>Un producto para cada necesidad</Title><Thumbnail>http://litofinter.es.milfoil.arvixe.com/Thumbnail/Book3.png</Thumbnail><pdf>http://litofinter.es.milfoil.arvixe.com/PDF/Book6.pdf</pdf></Product><Product><pid>58</pid><Title>Quitamanchas pistola</Title><Thumbnail>http://litofinter.es.milfoil.arvixe.com/Thumbnail/Book9.png</Thumbnail><pdf>http://litofinter.es.milfoil.arvixe.com/PDF/Book7.pdf</pdf></Product></category></Table>
CODE
#TABLEVIEWCONTROLLER.H:
#class Book;
#interface TableViewController : UIViewController<UITableViewDataSource,UITableViewDelegate> {
IBOutlet UIButton *btnBack;
IBOutlet UITableView *tableView;
Book *bookOne;
NSMutableArray *array;
}
-(IBAction)onTapBack;
#property (nonatomic, retain)IBOutlet UITableView *tableView;
#end
#TABLEVIEWCONTROLLER.M
import "TableViewController.h"
import "XMLTableAppDelegate.h"
import "Book.h"
#implementation TableViewController
#synthesize tableView;
-(IBAction)onTapBack
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Message from mAc" message:#"Trail" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok",nil];
[alert show];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
Book *book = [[Book alloc]init];
book = [array objectAtIndex:indexPath.row];
cell.textLabel.text = book.arrayString;
[book release];
[cell autorelease];
return cell;
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
tableView.delegate = self;
tableView.dataSource = self;
//bookOne = [[Book alloc]init];
array = [[NSMutableArray alloc]init];
[array addObject:#"mAc"];
[array addObject:#"Mayank"];
[array addObject:#"Manu"];
}
-(void)viewWillAppear:(BOOL)animated{
[tableView reloadData];
}
- (void)dealloc {
[super dealloc];
[tableView release];
[btnBack release];
}
#BOOK.h
#interface Book : NSObject {
NSMutableString *arrayString;
}
#property(nonatomic,retain) NSMutableString *arrayString;
#end
#BOOK.M
import "Book.h"
#implementation Book
#synthesize arrayString;
-(void)dealloc
{
[super dealloc];
[arrayString release];
}
#end

You shouldn't alloc+init memory for Book and don't release it : [book release];
Your array contains objects of class NSString : [array addObject:#"mAc"];
Try to set value using next line: cell.textLabel.text = [array objectAtIndex:indexPath.row];

You do like this,
book.arrayString= [array objectAtIndex:indexPath.row];
This also shows the data you added by your own (ie) that mAc,Mayank and something.
Otherwise You diectly add the value like
Cell.textLabel.text=[array objectAtIndex:indexPath.row];

Related

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!!!!!!!

Error when implementing MWFeedParser

I trying to use the MWFeedParser library. I think the problem is that I want to use a view controller with a table view to display the news. Now there comes nothing up in my table view when launching the app. The code for the news view controller looks like this:
.H:
#import "MWFeedItem.h"
#import "MWFeedParser.h"
#interface NewsViewController : UIViewController <MWFeedParserDelegate> {
IBOutlet UILabel *label;
// 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;
#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
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
// Date
// Setup
self.title = #"News";
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.website.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
In IB, I've dragged a table view onto the view and linked it to dataSource and delegate. But nothing shows up in the table view.
Would really appreciate some answers/ideas!
Thanks.
i think you should uncomment the following line in your "updateTableWithParsedItems" method:
[self.tableView reloadData];

Single Text from two different UITableView

I have two UITableview's and if i select a one row in each table, the textLabel.text of that particular row should display in a single UIAlertview.
How can i combine the textLabel.textof two tables and display in one UIAlertView
Can anyone let me know how can i do this
EX: one Table view which displays A, B, C, D and one more tableView Which Shows 1,2,3,4.
This two table are from different class's. now suppose if i press a row in table 1 i will get textLabel.text as 'A' and if i press table 2 i will get textLabel.text as '1' now on the view if a select A in table1 and 1 in table 2 i should get a AlertView showing message as 'A1'
Code for reference:
viewController.h
#import <UIKit/UIKit.h>
#import "FirstTVContoller.h"
#import "SecondTVController.h"
#interface TwoTableViewsViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>{
FirstTVContoller *firstController;
SecondTVController *secondController;
IBOutlet UITableView *firstTable;
IBOutlet UITableView *secondTable;
NSString *stringTable1;
NSString *stringTable2;
NSArray * myArray1;
NSArray * myArray2;
}
#property (nonatomic, retain) NSString *stringTable1;
#property (nonatomic, retain) NSString *stringTable2;
#property (nonatomic, retain) NSArray * myArray1;
#property (nonatomic, retain) NSArray * myArray2;
#end
.m:
#import "TwoTableViewsViewController.h"
#implementation TwoTableViewsViewController
#synthesize stringTable1 = stringTable1;
#synthesize stringTable2 = stringTable2;
#synthesize myArray1,myArray2;
- (void)viewDidLoad {
[super viewDidLoad];
if (firstController == nil) {
firstController = [[FirstTVContoller alloc] init];
}
if (secondController == nil) {
secondController = [[SecondTVController alloc] init];
}
[firstTable setDataSource:firstController];
[secondTable setDataSource:secondController];
[firstTable setDelegate:firstController];
[secondTable setDelegate:secondController];
firstController.view = firstController.tableView;
secondController.view = secondController.tableView;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if (tableView == firstTable) {
self.stringTable1 = [myArray1 objectAtIndex: indexPath.row];
//call uiAlert, and place the stringTable1 on your message
if (tableView == secondTable) {
self.stringTable2 = [myArray2 objectAtIndex: indexPath.row];
//call uiAlert, and place the stringTable2 on your message
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"hi" message:[NSString stringWithFormat:#"%# %#", self.stringTable1, self.stringTable2] delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[firstController release];
[secondController release];
[firstTable release];
[secondTable release];
[stringTable1 release];
[stringTable2 release];
[super dealloc];
}
#end
table1:
#import <Foundation/Foundation.h>
#interface FirstTVContoller : UITableViewController <UITableViewDataSource, UITableViewDelegate>{
NSMutableArray *items;
}
#end
#import "FirstTVContoller.h"
#import "SecondTVController.h"
#implementation FirstTVContoller
-(void) loadView
{
if (items == nil) {
items = [[NSMutableArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",#"6",#"8",#"9",#"10",#"11",#"12",#"13",#"14",#"15",#"16",#"17",nil] retain];
}
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
return [items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyIdentifier"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewStylePlain reuseIdentifier:#"MyIdentifier"];
}
cell.textLabel.text = [NSString stringWithFormat:#"1.%#" ,[items objectAtIndex:indexPath.row]];
return cell;
}
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString *stringVariable = cell.textLabel.text;
NSLog(#"%#",stringVariable);
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tv commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
if(editingStyle == UITableViewCellEditingStyleDelete) {
//Delete the object from the table.
[items removeObjectAtIndex:indexPath.row];
[tv deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
-(void) dealloc
{
[items release];
[super dealloc];
}
#end
Table2:
#import <Foundation/Foundation.h>
#interface SecondTVController : UITableViewController <UITableViewDataSource, UITableViewDelegate>{
int numberOfCells;
}
#end
#import "SecondTVController.h"
#implementation SecondTVController
-(void) viewDidLoad
{
numberOfCells = 20;
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
return numberOfCells;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyIdentifier"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellSelectionStyleNone reuseIdentifier:#"MyIdentifier"];
}
cell.textLabel.text = [NSString stringWithFormat:#"2.%d", indexPath.row];
return cell;
}
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString *stringVariable = cell.textLabel.text;
NSLog(#"%#",stringVariable);
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tv commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
if(editingStyle == UITableViewCellEditingStyleDelete) {
//Delete the object from the table.
numberOfCells -=1;
[tv deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
}
}
#end
Kindly Suggest
Is not clear to me when you want your alertView shown,
but this will help you
you need to have a property for placing the text of your labels
so on your .h
# interface MyViewController :UIViewController {
NSString *_stringTable1;
NSString *_stringTable2;
}
#property (nonatomic, retain) NSString *stringTable1;
#property (nonatomic, retain) NSString *stringTable2;
on your .m
#synthesize stringTable1 = _stringTable1;
#synthesize stringTable2 = _stringTable2;
- (void) dealloc{
[_stringTable1 release];
[_stringTable2 release];
[super dealloc];
}
so on your table delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (tableView == table1) {
self.stringTable1 = [myArray1 objectAtIndex: indexPath.row];
//call uiAlert, and place the stringTable1 on your message
}
if (tableView == table2) {
self.stringTable2 = [myArray2 objectAtIndex: indexPath.row];
//call uiAlert, and place the stringTable2 on your message
}
}
when you call your uiAlertView, for the message you can just show them togheter like
[NSString stringWithFormat:#"%# %#", self.stringTable1, self.stringTable2];
//Combine two string in one string on the tap of second table cell tap event...
//Use following code in didSelectRowAtIndexPath method..and enjoy...
NSString *tempstring = [[NSString alloc]init];
tempstring =yourlable.text;// your cell label...
if (textField.tag == 1) {
NSUserDefaults *stringsaver = [NSUserDefaults standardUserDefaults];
if([stringsaver objectForKey:#"stringsaver"]== nil)
{
[stringsaver setObject:tempstring forKey:#"stringsaver"];
}
else
{
NSString *combinedstring = [stringsaver objectForKey:#"stringsaver"];
//NSLog(#"==%#",combinedstring);
UIAlertView *alertdata = [[UIAlertView alloc]
initWithTitle:#"Your Title"
message:combinedstring
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertdata show];
[alertdata release];
[stringsaver removeObjectForKey:#"stringsaver"];
}
Try this-
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell * cell1 = [tableView cellForRowAtIndexPath:indexPath];
// get here the instance of otherTableView.
UITableViewCell * cell2 = [otherTableView cellForRowAtIndexPath:indexPath];
UILabel *Title1 = (UILabel *)[cell1 viewWithTag:1]; //for it you need to make the label with Tag 1
UILabel *Title2 = (UILabel *)[cell2 viewWithTag:1]; //for it you need to make the label with Tag 1
NSString * str = [NSString stringWithFormat:#"%# %#",[Title1 text],[Title2 text]];
//fire the alert
UIAlertView *alertdata = [[UIAlertView alloc]
initWithTitle:#"Your Title"
message:str
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertdata show];
}

UITableView does not show new entries when data object conforms to NSCoding

When I make an object class conform to NSCoding, the tableView does not show new entries. Suspected it had to do with the object initialization but cannot solve it. Might be very basic but cannot find the error. Here is the code I simplified to post:
Custom Object:
// DataObject.h
#import <Foundation/Foundation.h>
#interface DataObject : NSObject {
NSString *name;
}
#property (nonatomic, copy) NSString *name;
#end
// DataObject.m
#import "DataObject.h"
#implementation DataObject
#synthesize name;
- (void)encodeWithCoder:(NSCoder*)encoder {
[encoder encodeObject:name forKey:#"name"];
}
- (id)initWithCoder:(NSCoder *)decoder {
self = [super init];
if (!self) return nil;
name = [[decoder decodeObjectForKey:#"name"] retain];
return self;
}
These is the TableView root controller - Have omitted a few methods:
// RootViewController.h
#import <UIKit/UIKit.h>
#interface RootViewController : UITableViewController {
NSMutableArray *list;
}
#property (nonatomic, retain) NSMutableArray *list;
- (void)add:(id)sender;
- (NSString *)dataFilePath;
#end
// RootViewController.m
#import "RootViewController.h"
#import "DataObject.h"
#implementation RootViewController
#synthesize list;
- (void)add:(id)sender
{
DataObject *newEntry = [[DataObject alloc] init];
newEntry.name = #"Willy";
[self.list addObject:newEntry];
[self.tableView reloadData];
// Scroll table view to last row
if ([list count] > 1) {
NSUInteger index = list.count - 1;
NSIndexPath *lastRow = [NSIndexPath indexPathForRow:index inSection: 0];
[self.tableView scrollToRowAtIndexPath: lastRow atScrollPosition: UITableViewScrollPositionTop animated: YES];
}
[newEntry release];
}
- (NSString *)dataFilePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:#"datafile"];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
self.title = #"Names";
self.list = [[NSMutableArray alloc] init];
NSMutableArray *tempArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[self dataFilePath]];
self.list = tempArray;
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(applicationWillResignActive:)
name:UIApplicationWillResignActiveNotification
object:app];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
self.navigationItem.rightBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc]
initWithTitle:#"Add"
style:UIBarButtonItemStylePlain
target:self
action:#selector(add:)];
self.navigationItem.leftBarButtonItem = addButton;
[addButton release];
[self.tableView reloadData];
}
- (void)applicationWillResignActive:(NSNotification *)notification;
{
[NSKeyedArchiver archiveRootObject:self.list toFile:[self dataFilePath]];
}
- (void)viewWillAppear:(BOOL)animated {
[self.tableView reloadData];
[super viewWillAppear:animated];
}
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [list 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.
NSUInteger row = [indexPath row];
DataObject *oneName = [self.list objectAtIndex:row];
cell.textLabel.text = oneName.name;
return cell;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source.
NSUInteger row = [indexPath row];
[self.list removeObjectAtIndex:row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
#end
Oh, man I am so embarrassed...It had nothing to do with NSCoding directly but when I made the data class NSCoding compliant I added in viewDidLoad:
NSMutableArray *tempArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[self dataFilePath]];
self.list = tempArray;
The first line is fine, but the second assigned a new pointer address to self.list and the tempArray was later autoreleased...
As this line was not executed in the "not NSCoding compliant" version it appeared to work then and not when encodeWithCoder and initWithCoder were implemented.
Because of this self.list was nil instead of being initialized and ready when in the add: method I added a new instance. It was created fine, but never added to the array and therefore never showed in the tableView.
This was easily fixed using instead in viewDidLoad:
NSMutableArray *tempArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[self dataFilePath]];
[self.list addObjectsFromArray:tempArray];
Worst part is that I was pulling my hair because of this and was convinced it was because of NSCoding and the initialization of objects...

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