I am trying to populate a list of XML data in my tableview. There is a Uiviewcontroller which holds the tableview, one xmlparser which download and parse data and a class which holds the properties of the XML data.
UIViewcontroller.h
#import <UIKit/UIKit.h>
#import "XMLParser.h"
#interface TableViewTutViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {
IBOutlet UITableView *myTableView;
XMLParser *xmlParser;
EnquiryData *currentEnquiry;
}
#property (nonatomic, retain) IBOutlet UITableView *myTableView;
#property(nonatomic, retain) XMLParser *xmlParser;
#property(nonatomic, retain) EnquiryData *currentEnquiry;
#end
UIViewcontroller.m
#import "TableViewTutViewController.h"
#import "EnquiryViewController.h"
#import "AppDelegate.h"
#implementation TableViewTutViewController
#synthesize xmlParser;
#synthesize myTableView;
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(void)viewDidLoad
{
AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *welcome= #"Welcome ";
welcome= [welcome stringByAppendingString:app.firstname];
NSString *url = #"http://demos4clients.com/iphone/csi/register.php?choice=getEnquiryList&id_user=";
url = [url stringByAppendingString:app.id_user];
xmlParser = [[XMLParser alloc] loadXMLByURL:url];
[super viewDidLoad];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(section == 0 || section == 1)
return 1;
else{
NSLog(#"%i", [[self.xmlParser datas]count]);
int i = (int)[[self.xmlParser datas] count];
i++;
return i;
}
}
- (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];
cell.textLabel.highlightedTextColor = [UIColor yellowColor];
}
if(indexPath.section == 0){
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:20];
cell.textLabel.text = #"Add Enquiry";
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
cell.selectionStyle = UITableViewCellAccessoryNone;
}
if(indexPath.section == 1)
{
if(indexPath.row == 0)
{
cell.textLabel.text = #"Enquiry";
UIImage *accept= [UIImage imageNamed:#"accept_ico.png"];
UIButton *acceptButton = [UIButton buttonWithType:UIButtonTypeCustom];
acceptButton.frame = CGRectMake(110, 10, 20, 21);
[acceptButton.layer setBorderWidth:0];
[acceptButton setBackgroundImage:accept forState:UIControlStateNormal];
[acceptButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:acceptButton];
[acceptButton release];
[accept release];
UIImage *view= [UIImage imageNamed:#"view_ico.png"];
UIButton *viewButton = [UIButton buttonWithType:UIButtonTypeCustom];
viewButton.frame = CGRectMake(190, 10, 20, 21);
[viewButton.layer setBorderWidth:0];
[viewButton setBackgroundImage:view forState:UIControlStateNormal];
[viewButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:viewButton];
[viewButton release];
[view release];
UIImage *new= [UIImage imageNamed:#"new_ico.png"];
UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom];
newButton.frame = CGRectMake(270, 10, 20, 21);
[newButton.layer setBorderWidth:0];
[newButton setBackgroundImage:new forState:UIControlStateNormal];
[newButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:newButton];
[new release];
[newButton release];
}
}
if(indexPath.section == 2){
currentEnquiry = [[xmlParser datas] objectAtIndex:indexPath.row];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:20];
cell.textLabel.text = currentEnquiry.makeCar;
[currentEnquiry release];
UILabel * acceptLabel = [[UILabel alloc] initWithFrame:CGRectMake(110, 8, 30, 30)];
acceptLabel.backgroundColor = [UIColor clearColor];
acceptLabel.textAlignment = UITextAlignmentCenter; // UITextAlignmentCenter, UITextAlignmentLeft
acceptLabel.textColor=[UIColor blueColor];
acceptLabel.numberOfLines=0;
acceptLabel.lineBreakMode=UILineBreakModeWordWrap;
acceptLabel.text = #"12";
[cell.contentView addSubview:acceptLabel];
[acceptLabel release];
UILabel * viewLabel = [[UILabel alloc] initWithFrame:CGRectMake(190, 8, 30, 30)];
viewLabel.backgroundColor = [UIColor clearColor];
viewLabel.textAlignment = UITextAlignmentCenter; // UITextAlignmentCenter, UITextAlignmentLeft
viewLabel.textColor=[UIColor blueColor];
viewLabel.numberOfLines=0;
viewLabel.lineBreakMode=UILineBreakModeWordWrap;
viewLabel.text = #"1";
[cell.contentView addSubview:viewLabel];
[viewLabel release];
UILabel * newLabel = [[UILabel alloc] initWithFrame:CGRectMake(270, 8, 30, 30)];
newLabel.backgroundColor = [UIColor clearColor];
newLabel.textAlignment = UITextAlignmentCenter; // UITextAlignmentCenter, UITextAlignmentLeft
newLabel.textColor=[UIColor blueColor];
newLabel.numberOfLines=0;
newLabel.lineBreakMode=UILineBreakModeWordWrap;
newLabel.text = #"5";
[cell.contentView addSubview:newLabel];
[newLabel release];
}
return cell;
}
#end
XML.h
#import <Foundation/Foundation.h>
#interface EnquiryData : NSObject
{
NSString *makeCar;
NSString *modelCar;
NSString *yearCar;
NSString *minPrice;
NSString *maxPrice;
NSString *minRun;
NSString *maxRun;
NSString *location;
NSString *fuelType;
NSString *searchRadius;
}
#property (nonatomic, retain) NSString *makeCar;
#property (nonatomic, retain) NSString *modelCar;
#property (nonatomic, retain) NSString *yearCar;
#property (nonatomic, retain) NSString *minPrice;
#property (nonatomic, retain) NSString *maxPrice;
#property (nonatomic, retain) NSString *minRun;
#property (nonatomic, retain) NSString *maxRun;
#property (nonatomic, retain) NSString *location;
#property (nonatomic, retain) NSString *fuelType;
#property (nonatomic, retain) NSString *searchRadius;
#end
XML..m file
#import "EnquiryData.h"
#implementation EnquiryData
#synthesize makeCar;
#synthesize modelCar;
#synthesize yearCar;
#synthesize minPrice;
#synthesize maxPrice;
#synthesize minRun;
#synthesize maxRun;
#synthesize searchRadius;
#synthesize location;
#synthesize fuelType;
#end
parser(.h) file
#import <Foundation/Foundation.h>
#import "EnquiryData.h"
#interface XMLParser : NSObject<NSXMLParserDelegate>
{
NSMutableString *currentNodeContent;
NSMutableArray *datas;
NSXMLParser *parser;
EnquiryData *recentEnquiry;
}
#property (readonly, retain) NSMutableArray *datas;
-(id) loadXMLByURL:(NSString *)urlString;
#end
parser.m
#import "XMLParser.h"
#implementation XMLParser
#synthesize datas;
-(id) loadXMLByURL:(NSString *)urlString
{
datas = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
parser = [[NSXMLParser alloc] initWithData:data];
parser.delegate = self;
[parser parse];
return self;
}
- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementname namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementname isEqualToString:#"enquiry"])
{
recentEnquiry = [EnquiryData alloc];
}
}
- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementname namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementname isEqualToString:#"make"])
{
recentEnquiry.makeCar = currentNodeContent;
}
if ([elementname isEqualToString:#"model"])
{
recentEnquiry.modelCar = currentNodeContent;
}
if ([elementname isEqualToString:#"model_yr"])
{
recentEnquiry.yearCar = currentNodeContent;
}
if ([elementname isEqualToString:#"min_price"])
{
recentEnquiry.minPrice = currentNodeContent;
}
if ([elementname isEqualToString:#"max_price"])
{
recentEnquiry.maxPrice = currentNodeContent;
}
if ([elementname isEqualToString:#"min_run"])
{
recentEnquiry.minRun = currentNodeContent;
}
if ([elementname isEqualToString:#"max_run"])
{
recentEnquiry.maxRun = currentNodeContent;
}
if ([elementname isEqualToString:#"fuel_type"])
{
recentEnquiry.fuelType = currentNodeContent;
}
if ([elementname isEqualToString:#"location"])
{
recentEnquiry.location = currentNodeContent;
}
if ([elementname isEqualToString:#"search_radius"])
{
recentEnquiry.searchRadius = currentNodeContent;
[datas addObject:recentEnquiry];
}
}
- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
currentNodeContent = (NSMutableString *) [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
#end
You have use the release statement with out allocation
when ever you allocate the memory for object then only use for release statement for that object
For Ex: UIButton *btn = [UIButton alloc]init];
then release the end of button usage [btn release];
Once Crass check this statement [currentEnquiry release]; also
Implement this parser delegate method in your XMLParser .m file:
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
[[NSNotificationCenter defaultCenter] postNotificationName:#"ReloadTable" object:nil];
}
Set numberOfRows integer variable to Zero in ViewController.m viewDidLoad method
-(void)viewDidLoad
{
numberOfRows = 0;
AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *welcome= #"Welcome ";
welcome= [welcome stringByAppendingString:app.firstname];
NSString *url = #"http://demos4clients.com/iphone/csi/register.php?choice=getEnquiryList&id_user=";
url = [url stringByAppendingString:app.id_user];
xmlParser = [[XMLParser alloc] loadXMLByURL:url];
[super viewDidLoad];
}
Implement Observer for this notification in ViewController.m viewWillAppear method i.e.
-(void)viewWillAppear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(reloadTable:) name:#"ReloadTable" object:nil];
}
- (void)reloadTable: (NSNotification *)notif
{
numberOfRows = [[self.xmlParser datas]count];
[table reloadData];
}
Implement remove Observer for this notification in ViewController.m viewWillDisappear method i.e.
- (void)viewWillDisappear:(BOOL)animated{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
In UITableView datasource Method for number Of Rows In Section implement this way:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(numberOfRows == 0)
return 0;
return (section == 0 || section == 1) ? 1 : numberOfRows + 1;
}
I am sure you will not get exe bad access problem
Related
I want to pass 2 string selected from UITableview (CompleteView) to new UIView (DetailView)
This is my code:
In CompleteView.h()
#property (nonatomic, retain) NSString *memoString;
#property (nonatomic, retain) NSString *previewString;
In Completeview.m()
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
previewString = [PreviewArray objectAtIndex:indexPath.row];
NSLog(#"Preview string %#",previewString);
memoString = [MemoArray objectAtIndex:indexPath.row];
NSLog(#"Memo string %#",memoString);
DetailView *detailAlert = [[DetailView alloc] initWithFrame:CGRectMake(10, 40, 300, 300)];
detailAlert.strPreview =previewString ;
detailAlert.strMemo = memoString;
[self.view addSubview:detailAlert];
[detailAlert show];
[detailAlert release];
}
In DetailView()
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
originalFrame = frame;
UIWebView *videoview = [[UIWebView alloc] initWithFrame:CGRectMake(10,80,275.0,150)];
NSString *url=[NSURL URLWithString:strPreview];
NSURL *nsurl=[NSURL URLWithString:url];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[videoview loadRequest:nsrequest];
[self addSubview:videoview];
return self;
}
In DetailView.h
#property (nonatomic, retain) NSString* strMemo;
#property (nonatomic, retain) NSString* strPreview;
When run, previewString not send to DetailView. I'm debug, when run strPreview and strMemo in DetailView is 0x00000. Thanks in advance
You can pass custom Initialisers like below . If you wish you can add one parameter
to custom Initialisers
In CompleteView.h()
#property (nonatomic, retain) NSString *memoString;
#property (nonatomic, retain) NSString *previewString;
In Completeview.m()
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
previewString = [PreviewArray objectAtIndex:indexPath.row];
NSLog(#"Preview string %#",previewString);
memoString = [MemoArray objectAtIndex:indexPath.row];
NSLog(#"Memo string %#",memoString);
DetailView *detailAlert = [[DetailView alloc] initWithFrame:CGRectMake(10, 40, 300, 300) andPreviewstring:previewString];
detailAlert.strPreview =previewString ;
detailAlert.strMemo = memoString;
[self.view addSubview:detailAlert];
[detailAlert show];
[detailAlert release];
}
In DetailView()
- (id)initWithFrame:(CGRect)frame andPreviewstring:(NSString *)stPreview
{
self = [super initWithFrame:frame];
if (self) {
originalFrame = frame;
UIWebView *videoview = [[UIWebView alloc] initWithFrame:CGRectMake(10,80,275.0,150)];
NSString *url=[NSURL URLWithString:strPreview];
NSURL *nsurl=[NSURL URLWithString:url];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[videoview loadRequest:nsrequest];
[self addSubview:videoview];
return self;
}
In DetailView.h
#property (nonatomic, retain) NSString* strMemo;
#property (nonatomic, retain) NSString* strPreview;
- (id)initWithFrame:(CGRect)frame andPreviewstring:(NSString *)stPreview;
try this:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
previewString = [PreviewArray objectAtIndex:indexPath.row];
NSLog(#"Preview string %#",previewString);
memoString = [MemoArray objectAtIndex:indexPath.row];
NSLog(#"Memo string %#",memoString);
DetailView *detailAlert = [[DetailView alloc] initWithFrame:CGRectMake(10, 40, 300, 300)];
detailAlert.strPreview =previewString ;
detailAlert.strMemo = memoString;
[detailAlert createWebView];
[self.view addSubview:detailAlert];
[detailAlert show];
[detailAlert release];
}
write code for string allocation
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
originalFrame = frame;
//add following two lines
strPreview = [[NSString alloc] init];
strMemo = [[NSString alloc] init];
//........
return self;
}
-(void) createWebView {
UIWebView *videoview = [[UIWebView alloc] initWithFrame:CGRectMake(10,80,275.0,150)];
NSString *url=[NSURL URLWithString:strPreview];
NSURL *nsurl=[NSURL URLWithString:url];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[videoview loadRequest:nsrequest];
[self addSubview:videoview];
}
The problem here is you are setting two properties in detail view after initializing DetailView. But you are trying to use a property values within the initializer which are yet to be set.
As I can see there are two options you can try out.
Write another initializer which accept these two properties. So that you can use those two properties in that initializer.
(id)initWithFrame:(CGRect)frame strMemo:(NSString *)memo strPreview:(NSString *)preview {
self = [super initWithFrame:frame];
if (self) {
originalFrame = frame;
UIWebView *videoview = [[UIWebView alloc] initWithFrame:CGRectMake(10,80,275.0,150)];
NSString *url=[NSURL URLWithString:preview];
NSURL *nsurl=[NSURL URLWithString:url];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[videoview loadRequest:nsrequest];
[self addSubview:videoview];
return self;
}
Or else you can extract the logic in the current initializer and put them in to a separate method which you can called after setting two properties from the CompleteView.
I want load data to tableview from my web service in my iphone application. All outputs are working correctly but my table doesn't contain any data. It is empty.
I did not find any mistake in the application. Why doesn't the tableview load data from the web service ?
ScoreClass.h
#interface ScoreClass : NSObject {
IBOutlet NSInteger *ScoreID;
IBOutlet NSInteger *UserScore;
IBOutlet NSInteger *GameID;
IBOutlet NSString *MacID;
IBOutlet NSString *NickName;
IBOutlet Boolean *IsDeleted;
IBOutlet NSDate *CreatedOn;
IBOutlet NSDate *ModifiedOn;
NSMutableArray *ScoreList;
}
#property(assign, readwrite) NSInteger *ScoreID;
#property(assign, readwrite) NSInteger *UserScore;
#property(assign, readwrite) NSInteger *GameID;
#property(nonatomic, retain) NSString *MacID;
#property(nonatomic, retain) NSString *NickName;
#property(nonatomic, assign) Boolean *IsDeleted;
#property(nonatomic, retain) NSDate *CreatedOn;
#property(nonatomic, retain) NSDate *ModifiedOn;
#property(retain, readwrite) NSMutableArray *ScoreList;
#end
ScoreClass.m
#import "ScoreClass.h"
#implementation ScoreClass
#synthesize ScoreID, UserScore, GameID, MacID, NickName, IsDeleted,CreatedOn, ModifiedOn,ScoreList;
-(id)init {
[super init];
MacID = [NSString stringWithFormat:#""];
NickName= [NSString stringWithFormat:#""];
return self;
}
-(void) dealloc{
[MacID release];
[NickName release];
[super dealloc];
}
#end
ScoreWebService.h
#import <UIKit/UIKit.h>
#import "ScoreClass.h"
#interface ScoreWebService : UIViewController {
// Request
NSString *address;
NSString *xmlNamespace;
NSString *operation;
NSString *parameters;
NSMutableString *inComeValue;
// Connection
BOOL recordResults;
BOOL connectionFinished;
// Xml Parsing
NSMutableString *soapResults;
NSMutableData *webData;
NSXMLParser *xmlParser;
ScoreClass *score;
NSMutableArray *ScoreList;
}
#property(nonatomic, retain) NSString *address;
#property(nonatomic, retain) NSString *xmlNamespace;
#property(nonatomic, retain) NSString *operation;
#property(nonatomic, retain) NSString *parameters;
#property(nonatomic, retain) NSMutableString *inComeValue;
#property(retain, readwrite) NSMutableArray *ScoreList;
#property(nonatomic, retain) ScoreClass *score;
#end
ScoreWebService.m
#import "ScoreWebService.h"
#implementation ScoreWebService
#synthesize operation, parameters, address, xmlNamespace, inComeValue, score;
#synthesize ScoreList;
-(id)init {
[super init];
address = [NSString stringWithFormat:#""];
xmlNamespace = [NSString stringWithFormat:#""];
operation = [NSString stringWithFormat:#""];
parameters = [NSString stringWithFormat:#""];
inComeValue = [NSString stringWithFormat:#""];
score = [[ScoreClass alloc]init];
ScoreList = [[NSMutableArray alloc]init];
return self;
}
-(NSMutableArray *)ScoreTableWebService{
if (([address isEqualToString:#""]) || ([xmlNamespace isEqualToString:#""]) || ([operation isEqualToString:#""])) {
//return;
}
recordResults = FALSE;
NSString *soapMessage = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<BayiSatisTakipTablo6Oku xmlns=\"http://trigonservis.com/\">"
"<IstasyonKodu>34005</IstasyonKodu>"
"<Gun1>02.01.2012</Gun1>"
"</BayiSatisTakipTablo6Oku>"
"</soap:Body>"
"</soap:Envelope>"
];
NSLog(#"Request SOAP = \n%#\n\n", soapMessage);
NSURL *url = [NSURL URLWithString:address];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://trigonservis.com/BayiSatisTakipTablo6Oku" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: soapMessage forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
//Connexion
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection ) {
webData = [[NSMutableData data] retain];
}
else {
NSLog(#"there is a problem to connect webservices");
}
while (!connectionFinished) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
return ScoreList;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
#if(TARGET_IPHONE_SIMULATOR)
NSLog(#"Reponse SOAP = \n%#\n\n", theXML);
#endif
[theXML release];
// Appel futur du parser
if(xmlParser)
[xmlParser release];
// Allocation du NSXMLParser
xmlParser = [[NSXMLParser alloc] initWithData: webData];
// Désigne l'instance de la classe courante comme étant le delegate du NSXMLParser
[xmlParser setDelegate: self];
[xmlParser setShouldResolveExternalEntities: YES];
[xmlParser parse];
[connection release];
[webData release];
connectionFinished = TRUE;
}
/************************************************************************************
** Connection */
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connection release];
[webData release];
}
/************************************************************************************
** XML Parsing
*/
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
attributes: (NSDictionary *)attributeDict {
NSLog(#"elementName = %# \n", elementName);
if( [elementName isEqualToString:#"DagiticiSatis"])
{
if(!soapResults)
soapResults = [[NSMutableString alloc] init];
recordResults = TRUE;
}
else if( [elementName isEqualToString:#"IstasyonAdi"])
{
if(!soapResults)
soapResults = [[NSMutableString alloc] init];
recordResults = TRUE;
}
return;
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if( recordResults ){
[soapResults appendString: string];
}
}
-(NSMutableArray *)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if( [elementName isEqualToString:#"DagiticiSatis"]) {
#if(TARGET_IPHONE_SIMULATOR)
NSLog(#"ScoreID = %# \n", soapResults);
#endif
score = [[ScoreClass alloc]init];
score.MacID = soapResults;
[soapResults release];
soapResults = nil;
}
else if( [elementName isEqualToString:#"IstasyonAdi"]){
#if(TARGET_IPHONE_SIMULATOR)
NSLog(#"IstasyonAdi = %# \n", soapResults);
#endif
score.NickName = soapResults;
[soapResults release];
soapResults = nil;
}
return ScoreList;
}
#end
GridTableViewCell.h
#import <UIKit/UIKit.h>
#interface GridTableViewCell : UITableViewCell {
UIColor *lineColor;
BOOL topCell;
UILabel *cell1;
UILabel *cell2;
UILabel *cell3;
}
#property (nonatomic, retain) UIColor* lineColor;
#property (nonatomic) BOOL topCell;
#property (readonly) UILabel* cell1;
#property (readonly) UILabel* cell2;
#property (readonly) UILabel* cell3;
#end
GridTableViewCell.m
#import "GridTableViewCell.h"
#define cell1Width 80
#define cell2Width 80
#define cellHeight 44
#implementation GridTableViewCell
#synthesize lineColor, topCell, cell1, cell2, cell3;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
topCell = NO;
// Add labels for the three cells
cell1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, cell1Width, cellHeight)];
cell1.textAlignment = UITextAlignmentCenter;
cell1.backgroundColor = [UIColor clearColor]; // Important to set or lines will not appear
[self addSubview:cell1];
cell2 = [[UILabel alloc] initWithFrame:CGRectMake(cell1Width, 0, cell2Width, cellHeight)];
cell2.textAlignment = UITextAlignmentCenter;
cell2.backgroundColor = [UIColor clearColor]; // Important to set or lines will not appear
[self addSubview:cell2];
cell3 = [[UILabel alloc] initWithFrame:CGRectMake(cell1Width+cell2Width, 0, 320-(cell1Width+cell2Width), cellHeight)]; // Note - hardcoded 320 is not ideal; this can be done better
cell3.textAlignment = UITextAlignmentCenter;
cell3.backgroundColor = [UIColor clearColor]; // Important to set or lines will not appear
[self addSubview:cell3];
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)dealloc
{
[cell1 release];
[cell2 release];
[cell3 release];
[super dealloc];
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, lineColor.CGColor);
// CGContextSetLineWidth: The default line width is 1 unit. When stroked, the line straddles the path, with half of the total width on either side.
// Therefore, a 1 pixel vertical line will not draw crisply unless it is offest by 0.5. This problem does not seem to affect horizontal lines.
CGContextSetLineWidth(context, 1.0);
// Add the vertical lines
CGContextMoveToPoint(context, cell1Width+0.5, 0);
CGContextAddLineToPoint(context, cell1Width+0.5, rect.size.height);
CGContextMoveToPoint(context, cell1Width+cell2Width+0.5, 0);
CGContextAddLineToPoint(context, cell1Width+cell2Width+0.5, rect.size.height);
// Add bottom line
CGContextMoveToPoint(context, 0, rect.size.height);
CGContextAddLineToPoint(context, rect.size.width, rect.size.height-0.5);
// If this is the topmost cell in the table, draw the line on top
if (topCell)
{
CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, rect.size.width, 0);
}
// Draw the lines
CGContextStrokePath(context);
}
- (void)setTopCell:(BOOL)newTopCell
{
topCell = newTopCell;
[self setNeedsDisplay];
}
#end
1 Set the delegate for table.
2 Assign data from web service to NSMutableArray.
3 Write method mentioned below.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//create cell here
}
4 call
[tblView reloadData];
I have the following code to fetch the data from URL, store it in arrays, and display it inside the table.
Now the issue is my URL which is feeding data to the tables changes according to the button click i.e. If user clicks button [gainer], data gets fetched from URL related to gainer and so on.
As I have called gainer method in didLoad method, initially data is displayed from the respective URL.But on button click no action is taken. The reason is I'm populating the arrays in methods (gainer and looser) but table is fetching data from the arrays at the time of table creation(and arrays are empty at that point).
I have created button in design view while I'm creating table programmatically.
fetchdataViewController.h
#import <UIKit/UIKit.h>
#interface fetchdataViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>{
IBOutlet UIWebView *webView;
NSMutableArray *arr1;
NSMutableArray *atarr;
NSMutableArray *arr2;
NSMutableArray *a;
NSMutableArray *b;
NSMutableArray *c;
NSMutableArray *d;
UITableView *aTableView;
}
-(IBAction)btnClicked:(id)sender;
-(IBAction)btnClicked1:(id)sender;
-(void)gainer;
-(void)looser;
#property(nonatomic,retain)NSMutableArray *arr1;
#property(nonatomic,retain)NSMutableArray *arr2;
#property(nonatomic,retain)NSMutableArray *atarr;
#property(nonatomic,retain)NSMutableArray *a;
#property(nonatomic,retain)NSMutableArray *b;
#property(nonatomic,retain)NSMutableArray *c;
#property(nonatomic,retain)NSMutableArray *d;
#property(nonatomic,retain)UIWebView *webView;
#property(nonatomic,retain)UITableView *aTableView;
#end
fetchdataViewController.m
#import "fetchdataViewController.h"
#implementation fetchdataViewController
NSMutableArray *atarr;
NSMutableArray *arr1;
NSMutableArray *arr2;
NSMutableArray *a;
NSMutableArray *b;
NSMutableArray *c;
NSMutableArray *d;
NSMutableString *mainstr;
NSMutableString *str;
#synthesize webView;
#synthesize arr1;
#synthesize arr2;
#synthesize atarr;
#synthesize a;
#synthesize b;
#synthesize c;
#synthesize d;
#synthesize aTableView;
int i,j;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [a count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier=#"Cell";
static NSInteger StateTag = 1;
static NSInteger CapitalTag = 2;
static NSInteger StateTag1 = 3;
static NSInteger StateTag2 = 4;
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil){
cell=[[[UITableViewCell alloc]initWithFrame:CGRectZero reuseIdentifier:CellIdentifier]autorelease];
CGRect frame;
frame.origin.x = 10;
frame.origin.y = 5;
frame.size.height = 35;
frame.size.width = 170;
UILabel *capitalLabel = [[UILabel alloc] initWithFrame:frame];
capitalLabel.tag = CapitalTag;
[cell.contentView addSubview:capitalLabel];
frame.origin.x += 125;
UILabel *stateLabel = [[UILabel alloc] initWithFrame:frame];
stateLabel.tag = StateTag;
[cell.contentView addSubview:stateLabel];
frame.origin.x += 100;
UILabel *stateLabel1 = [[UILabel alloc] initWithFrame:frame];
stateLabel1.tag = StateTag1;
[cell.contentView addSubview:stateLabel1];
frame.origin.x += 100;
UILabel *stateLabel2 = [[UILabel alloc] initWithFrame:frame];
stateLabel2.tag = StateTag2;
[cell.contentView addSubview:stateLabel2];
}
UILabel *capitalLabel = (UILabel *) [cell.contentView viewWithTag:CapitalTag];
UILabel *stateLabel = (UILabel *) [cell.contentView viewWithTag:StateTag];
UILabel *stateLabel1 = (UILabel *) [cell.contentView viewWithTag:StateTag1];
UILabel *stateLabel2 = (UILabel *) [cell.contentView viewWithTag:StateTag2];
capitalLabel.text=[a objectAtIndex:indexPath.row];
stateLabel.text = [b objectAtIndex:indexPath.row];
stateLabel1.text = [c objectAtIndex:indexPath.row];
stateLabel2.text = [d objectAtIndex:indexPath.row];
return cell;
}
-(IBAction)btnClicked:(id)sender{
[self gainer];
}
-(IBAction)btnClicked1:(id)sender {
[self looser];
}
-(void)gainer{
arr1=[[NSMutableArray alloc]init];
arr2=[[NSMutableArray alloc]init];
a=[[NSMutableArray alloc]init];
b=[[NSMutableArray alloc]init];
c=[[NSMutableArray alloc]init];
d=[[NSMutableArray alloc]init];
NSURL *url=[NSURL URLWithString:#"http://ipad.idealake.com/default.aspx?id=G"];
NSURLRequest *req=[NSURLRequest requestWithURL:url];
[webView loadRequest:req];
//storing page data in string
mainstr=[[NSMutableString alloc] initWithContentsOfURL:url];
atarr=[mainstr componentsSeparatedByString:#"#"];
NSString *str2;
NSString *str3;
for(int i=0; i<[atarr count]-1; i++)
{
// NSLog(#"i=:%i",i);
NSMutableString *str = [atarr objectAtIndex:i];
if (str!= nil)
arr1=[str componentsSeparatedByString:#";"];
for (int k=0;k<[arr1 count];k++)
{
str2 = [arr1 objectAtIndex:k];
[arr2 addObject:str2];
}
}
else
{
//NSLog (#"Nill");
}
}
for(int l=0;l<[arr2 count]/4;l++){
str3=[arr2 objectAtIndex:4*l];
[a addObject:str3];
str3=[arr2 objectAtIndex:(4*l)+1];
[b addObject:str3];
str3=[arr2 objectAtIndex:(4*l)+2];
[c addObject:str3];
str3=[arr2 objectAtIndex:(4*l)+3];
[d addObject:str3];
}
}
-(void)looser{
arr1=[[NSMutableArray alloc]init];
arr2=[[NSMutableArray alloc]init];
a=[[NSMutableArray alloc]init];
b=[[NSMutableArray alloc]init];
c=[[NSMutableArray alloc]init];
d=[[NSMutableArray alloc]init];
NSURL *url=[NSURL URLWithString:#"http://ipad.idealake.com/default.aspx?id=L"];
NSURLRequest *req=[NSURLRequest requestWithURL:url];
[webView loadRequest:req];
mainstr=[[NSMutableString alloc] initWithContentsOfURL:url];
atarr=[mainstr componentsSeparatedByString:#"#"];
NSString *str2;
NSString *str3;
for(int i=0; i<[atarr count]-1; i++)
{
NSMutableString *str = [atarr objectAtIndex:i];
if (str!= nil)
{
arr1=[str componentsSeparatedByString:#";"];
for (int k=0;k<[arr1 count];k++)
{
str2 = [arr1 objectAtIndex:k];
[arr2 addObject:str2];
}
}
else
{
//NSLog (#"Nill");
}
}
for(int l=0;l<[arr2 count]/4;l++){
str3=[arr2 objectAtIndex:4*l];
[a addObject:str3];
str3=[arr2 objectAtIndex:(4*l)+1];
[b addObject:str3];
str3=[arr2 objectAtIndex:(4*l)+2];
[c addObject:str3];
str3=[arr2 objectAtIndex:(4*l)+3];
[d addObject:str3];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
arr1=[[NSMutableArray alloc]init];
arr2=[[NSMutableArray alloc]init];
a=[[NSMutableArray alloc]init];
b=[[NSMutableArray alloc]init];
c=[[NSMutableArray alloc]init];
d=[[NSMutableArray alloc]init];
[self gainer];
[super viewDidLoad];
aTableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen]applicationFrame] style:UITableViewStyleGrouped];
aTableView.dataSource = self;
aTableView.delegate = self;
aTableView.frame = CGRectMake(0, 10, 720, 500);
[self.view addSubview:aTableView];
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (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 YES;
}
#end
UPDATE
When I run the below code, I get this output. That shaded grey portion is my main concern.
THANKS IN ADVANCE
You need to tell your UITableView that the data has changed by calling reloadData.
Use [self.tableview reloadData] after each change of url and with new arrays filled.
code:
check it:
#import <UIKit/UIKit.h>
#interface addsymptom : UITableViewController<UITableViewDelegate, UITableViewDataSource> {
NSMutableArray *listData;
}
#property(nonatomic,retain)NSMutableArray *listData;
#end
data.m:
============
#import "CustomCell.h"
#implementation addsymptom
#synthesize listData;
- (void)viewDidLoad
{
self.navigationItem.title= #"Symptoms";
self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"mainbg.png"]];
listData =[[NSMutableArray alloc] init];
[listData addObject:#"Backpain"];
[listData addObject:#"headache"];
[listData addObject:#"vomitting"];
[listData addObject:#"Bodypain"];
[listData addObject:#"thursday"];
[listData addObject:#"maleria"];
[listData addObject:#"Food poisioning"];
UIBarButtonItem *saveButton=[[UIBarButtonItem alloc]initWithTitle:#"save"
style:UIBarButtonSystemItemDone
target:self
action:#selector(save)];
self.navigationItem.rightBarButtonItem = saveButton;
[saveButton release];
[super viewDidLoad];
}
-(void)save {
[self.navigationController popViewControllerAnimated:YES];
}
- (UITableViewCell *)tableView:(UITableView *) tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CustomCell";
CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
for (id currentObject in topLevelObjects){
if ([currentObject isKindOfClass:[UITableViewCell class]]){
cell = (CustomCell *) currentObject;
break;
}
}
}
cell.textLabel.text = [listData objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (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
{
self.listData = nil;
}
- (void)dealloc
{
[super dealloc];
}
#end
custom cell.h:
==========
#import <Foundation/Foundation.h>
#interface CustomCell :UITableViewCell {
IBOutlet UILabel *textLabel;
IBOutlet UIButton *bttn;
BOOL isChecked;
NSString *ans;
}
#property (nonatomic,retain) IBOutlet UILabel *textLabel;
#property (nonatomic,assign) BOOL isChecked;
#property(nonatomic,assign)IBOutlet UIButton *bttn;
-(void)checkBoxClicked:(id)sender;
#end
customcell.m:
==============
#import "CustomCell.h"
#implementation CustomCell
#synthesize textLabel,bttn,isChecked;
-(id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithFrame:frame ]) {
textLabel = [[UILabel alloc]init];
textLabel.textAlignment = UITextAlignmentLeft;
}
return self;
}
NSString *ABC=NULL;
NSString *xyz=NULL;
-(void)checkBoxClicked:(id)sender{
UIButton *tappedButton = (UIButton*)sender;
if([tappedButton.currentImage isEqual:[UIImage imageNamed:#"NotSelected.png"]]) {
[sender setImage:[UIImage imageNamed: #"IsSelected.png"] forState:UIControlStateNormal];
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Message"
message:textLabel.text
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil,nil]autorelease];
[alert show];
ans = textLabel.text;
NSLog(#"%#",ans);
}
else {
[sender setImage:[UIImage imageNamed:#"NotSelected.png"]forState:UIControlStateNormal];
}
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
}
- (void)dealloc {
[super dealloc];
}
#end
check this example it has some implementation like yours
http://cocoawithlove.com/2009/01/multiple-row-selection-and-editing-in.html
best of luck
//CustomCell.h
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#interface CustomCell :UITableViewCell {
IBOutlet UILabel *textLabel;
IBOutlet UIButton *bttn;
BOOL isChecked;
NSString *ans;
}
#property (nonatomic,retain) IBOutlet UILabel *textLabel;
#property (nonatomic,assign) BOOL isChecked;
#property(nonatomic,assign)IBOutlet UIButton *bttn;
//-(void)checkBoxClicked:(id)sender;
#end
//CustomCell.m
#import "CustomCell.h"
#implementation CustomCell
#synthesize textLabel,bttn,isChecked;
-(id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithFrame:frame ]) {
textLabel = [[UILabel alloc]init];
textLabel.textAlignment = UITextAlignmentLeft;
}
return self;
}
NSString *ABC=NULL;
NSString *xyz=NULL;
//-(void)checkBoxClicked:(id)sender{
//
// UIButton *tappedButton = (UIButton*)sender;
//
//
// if([tappedButton.currentImage isEqual:[UIImage imageNamed:#"chkbox_unckd.png"]]) {
// [sender setImage:[UIImage imageNamed: #"chkbox_ckd.png"] forState:UIControlStateNormal];
// UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Message"
// message:textLabel.text
// delegate:self
// cancelButtonTitle:#"OK"
// otherButtonTitles:nil,nil]autorelease];
// [alert show];
//
// ans = textLabel.text;
//
//
// NSLog(#"%#",ans);
//
//
// }
//
// else {
// [sender setImage:[UIImage imageNamed:#"chkbox_unckd.png"]forState:UIControlStateNormal];
// }
//
//
//
//}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
// [bttn setImage:[UIImage imageNamed:#"chkbox_ckd.png"] forState:UIControlStateNormal];
[super setSelected:selected animated:animated];
}
- (void)dealloc {
[super dealloc];
}
#end
//addsymptom.h
#import <UIKit/UIKit.h>
#interface addsymptom : UIViewController<UITableViewDelegate, UITableViewDataSource> {
NSMutableArray *listData;
IBOutlet UITableView *table;
NSMutableArray *TitlesArray;
NSMutableArray *isCheckedArr;
}
#property(nonatomic,retain)NSMutableArray *listData;
- (void)saveTheChanges;
#end
//addsymptom.m
#import "addsymptom.h"
#import "CustomCell.h"
#implementation addsymptom
#synthesize listData;
- (void)viewDidLoad
{
self.navigationItem.title= #"Symptoms";
self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"mainbg.png"]];
listData =[[NSMutableArray alloc] init];
[listData addObject:#"Backpain"];
[listData addObject:#"headache"];
[listData addObject:#"vomitting"];
[listData addObject:#"Bodypain"];
[listData addObject:#"thursday"];
[listData addObject:#"maleria"];
[listData addObject:#"Food poisioning"];
UIBarButtonItem *saveButton=[[UIBarButtonItem alloc]initWithTitle:#"save" style:UIBarButtonSystemItemDone target:self action:#selector(saveTheChanges)];
isCheckedArr = [[NSMutableArray alloc] init];
for (int i=0; i<[listData count]; i++) {
[isCheckedArr addObject:#"0"];
}
self.navigationItem.rightBarButtonItem = saveButton;
[saveButton release];
TitlesArray = [[NSMutableArray alloc] init];
}
-(void)save {
[self.navigationController popViewControllerAnimated:YES];
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [listData count];
}
- (UITableViewCell *)tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CustomCell";
CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
for (id currentObject in topLevelObjects){
if ([currentObject isKindOfClass:[UITableViewCell class]]){
cell = (CustomCell *) currentObject;
break;
}
}
}
cell.textLabel.text = [listData objectAtIndex:indexPath.row];
[cell.bttn setTag:indexPath.row];
[cell.bttn addTarget:self action:#selector(updateCheckbox:) forControlEvents:UIControlEventTouchUpInside];
if ([[isCheckedArr objectAtIndex:indexPath.row] isEqualToString:#"1"])
{
[cell.bttn setImage:[UIImage imageNamed:#"chkbox_ckd.png"] forState:UIControlStateNormal];
}
else
{
[cell.bttn setImage:[UIImage imageNamed:#"chkbox_unckd.png"] forState:UIControlStateNormal];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (void)updateCheckbox:(id)sender {
if ([[isCheckedArr objectAtIndex:[sender tag]] isEqualToString:#"0"]) {
[isCheckedArr replaceObjectAtIndex:[sender tag] withObject:#"1"];
}
else if ([[isCheckedArr objectAtIndex:[sender tag]] isEqualToString:#"1"]) {
[isCheckedArr replaceObjectAtIndex:[sender tag] withObject:#"0"];
for (int i=0; i<[TitlesArray count]; i++) {
if ([[listData objectAtIndex:[sender tag]] isEqualToString:[TitlesArray objectAtIndex:i]]) {
[TitlesArray removeObjectAtIndex:i];
}
}
}
[table reloadData];
}
- (void)saveTheChanges {
for (int i=0; i<[isCheckedArr count]; i++) {
if ([[isCheckedArr objectAtIndex:i] isEqualToString:#"1"]) {
for (int j=0; j<[TitlesArray count]; j++) {
if ([[listData objectAtIndex:i] isEqualToString:[TitlesArray objectAtIndex:j]]) {
[TitlesArray removeObjectAtIndex:j];
}
}
[TitlesArray addObject:[listData objectAtIndex:i]];
}
}
for (int i=0; i<[TitlesArray count]; i++) {
NSLog(#"%#",[TitlesArray objectAtIndex:i]);
}
NSLog(#"=======");
}
- (void)viewDidUnload
{
// self.listData = nil;
}
- (void)dealloc
{
[listData release];
[TitlesArray release];
[isCheckedArr release];
[super dealloc];
}
#end
Does this post help, if you want Mail app style multiple selection of cells? Another post with great answers.
I load data into my UITableView from an NSXMLParser.
This all works fine but what I would like to implement is some short of activity when the App is loading the XML data, so it all is a bit more friendly for the users.
Some samples I have found still confuse me simply because I did not follow the same way of XMLParser implementation as most same do.
I provide my data here, please give some code samples on how I should put it in my code.
XMLParser.h:
#import <UIKit/UIKit.h>
#class DAFAppDelegate, Stage, Month;
#interface XMLParser : NSObject <NSXMLParserDelegate>
{
NSMutableString *currentElementValue;
DAFAppDelegate *appDelegate;
Stage *aStage;
Month *aMonth;
}
- (XMLParser *) initXMLParser;
+ (NSDate *)dateFromString:(NSString *)dateString;
+ (NSString *)stringFromDate:(NSDate *)stringDate;
#end
XMLParser.m:
#import "XMLParser.h"
#import "DAFAppDelegate.h"
#import "Stage.h"
#import "Month.h"
#implementation XMLParser
- (XMLParser *) initXMLParser
{
[super init];
appDelegate = (DAFAppDelegate *)[[UIApplication sharedApplication] delegate];
return self;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:#"Stages"])
{
//Initialize the array.
appDelegate.stages = [[NSMutableArray alloc] init];
}
if([elementName isEqualToString:#"Month"])
{
//Initialize the Month.
aMonth = [[Month alloc] init];
aMonth.stagesPerMonth = [[NSMutableArray alloc] init];
//Extract the attribute here.
aMonth.name = [attributeDict valueForKey:#"name"];
aMonth.monthID = [[attributeDict objectForKey:#"id"] integerValue];
NSLog(#"Reading Month id value :%i", aMonth.monthID);
NSLog(#"Reading Month name value :%#", aMonth.name);
}
if([elementName isEqualToString:#"Stage"])
{
//Initialize the Stage.
aStage = [[Stage alloc] init];
//Extract the attribute here.
aStage.stageID = [[attributeDict objectForKey:#"id"] integerValue];
NSLog(#"Reading id value :%i", aStage.stageID);
}
NSLog(#"Processing Element: %#", elementName);
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if(!currentElementValue)
{
currentElementValue = [[NSMutableString alloc] initWithString:string];
}
else
{
[currentElementValue appendString:string];
}
NSLog(#"Processing Value: %#", currentElementValue);
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
NSDate* date = [NSDate date];
NSDateFormatter* nsformatter = [[[NSDateFormatter alloc] init] autorelease];
[nsformatter setDateFormat:#"yyyy-MM-dd"];
NSDate* stageDate = [XMLParser dateFromString:aStage.end];
if([elementName isEqualToString:#"Stages"])
{
return;
}
if([elementName isEqualToString:#"Month"])
{
if (!aMonth.stagesPerMonth || aMonth.stagesPerMonth.count)
{
[appDelegate.stages addObject:aMonth];
}
[aMonth release];
aMonth = nil;
}
if([elementName isEqualToString:#"Stage"])
{
NSTimeInterval interval = [date timeIntervalSinceDate:stageDate];
if (interval < 0)
{
[aMonth.stagesPerMonth addObject:aStage];
}
[aStage release];
aStage = nil;
}
else
{
[aStage setValue:currentElementValue forKey:elementName];
[currentElementValue release];
currentElementValue = nil;
}
}
-(void) parserDidStartDocument:(NSXMLParser *)parser
{
NSLog(#"parserDidStartDocument");
}
-(void) parserDidEndDocument: (NSXMLParser *)parser
{
NSLog(#"parserDidEndDocument");
}
+ (NSDate *)dateFromString:(NSString *)dateString
{
NSDateFormatter *nsDateFormatter = [[NSDateFormatter alloc] init];
[nsDateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm"];
NSDate *date = [nsDateFormatter dateFromString:dateString];
return date;
[nsDateFormatter release];
}
+ (NSString *)stringFromDate:(NSDate *)stringDate
{
NSDateFormatter *stringDateFormatter = [[NSDateFormatter alloc] init];
NSLocale *nlLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"nl_NL"];
[stringDateFormatter setLocale:nlLocale];
[stringDateFormatter setDateFormat:#"EEE', 'dd MMMM yyyy HH:mma"];
NSString *dateString = [stringDateFormatter stringFromDate:stringDate];
return dateString;
[stringDateFormatter release];
}
- (void) dealloc
{
[aStage release];
[aMonth release];
[currentElementValue release];
[super dealloc];
}
#end
DAFAppDelegate.h:
#class RootViewController;
#interface DAFAppDelegate : NSObject <UIApplicationDelegate>
{
UIWindow *window;
UINavigationController *navigationController;
IBOutlet UITabBarController *rootTabController;
RootViewController *rootViewController;
NSMutableArray *stages;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet UITabBarController *rootTabController;
#property (nonatomic, retain) IBOutlet UINavigationController *navigationController;
#property (nonatomic, retain) IBOutlet RootViewController *rootViewController;
#property (nonatomic, retain) NSMutableArray *stages;
+ (void) showAlert;
#end
DAFAppDelegate.m:
#import "DAFAppDelegate.h"
#import "RootViewController.h"
#import "XMLParser.h"
#implementation DAFAppDelegate
#synthesize window;
#synthesize navigationController;
#synthesize rootViewController;
#synthesize rootTabController;
#synthesize stages;
+ (void) showAlert
{
UIAlertView *av = [[[UIAlertView alloc] initWithTitle:#"No Connection" message:#"Could not retrieve data" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] autorelease];
[av show];
}
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
NSURL *url = [[NSURL alloc] initWithString:#"http://web.me.com/ijar/Stages.xml"];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
//Initialize the delegate.
XMLParser *parser = [[XMLParser alloc] initXMLParser];
//Set delegate
[xmlParser setDelegate:parser];
//Start parsing the XML file.
BOOL success = [xmlParser parse];
if(success)
{
NSLog(#"No Errors");
}
else
{
[DAFAppDelegate showAlert];
NSLog(#"Error Error Error!!!");
}
[window addSubview:[rootTabController view]];
[window makeKeyAndVisible];
}
- (void)dealloc
{
[navigationController release];
[rootViewController release];
[rootTabController release];
[window release];
[stages release];
[super dealloc];
}
#end
RootViewController.h:
#class DAFAppDelegate;
#interface RootViewController : UITableViewController
{
DAFAppDelegate *appDelegate;
}
#end
RootViewController.m:
#import "RootViewController.h"
#import "DAFAppDelegate.h"
#import "DetailViewController.h"
#import "XMLParser.h"
#import "Stage.h"
#import "Month.h"
#import "AgendaCustomCell.h"
#implementation RootViewController
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
appDelegate = (DAFAppDelegate *)[[UIApplication sharedApplication] delegate];
self.title = NSLocalizedString(#"Agenda", #"Master view navigation title");
UIImageView *image=[[UIImageView alloc]initWithFrame:CGRectMake(0,0,45,45)] ;
[image setImage:[UIImage imageNamed:#"topBarIcon.png"]];
[self.navigationController.navigationBar.topItem setTitleView:image];
self.tableView.backgroundColor = [UIColor clearColor];
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [appDelegate.stages count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
Month *aMonth = [appDelegate.stages objectAtIndex:section];
return aMonth.name;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
Month *aMonth = [appDelegate.stages objectAtIndex:section];
return [aMonth.stagesPerMonth count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"AgendaCustomCell";
AgendaCustomCell *cell = (AgendaCustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
NSArray *topLevelObject = [[NSBundle mainBundle] loadNibNamed:#"AgendaCustomCell" owner:nil options:nil];
for (id currentObject in topLevelObject)
{
if ([currentObject isKindOfClass:[UITableViewCell class]])
{
cell = (AgendaCustomCell *)currentObject;
break;
}
}
}
Month *aMonth = [appDelegate.stages objectAtIndex:indexPath.section];
Stage *aStage = [aMonth.stagesPerMonth objectAtIndex:indexPath.row];
NSString *startDate = [XMLParser stringFromDate:[XMLParser dateFromString:aStage.start]];
NSString *endDate = [XMLParser stringFromDate:[XMLParser dateFromString:aStage.end]];
int endDateLength = endDate.length;
NSString *dateTitle = [NSString stringWithFormat:#"%# - %#", startDate, [endDate substringFromIndex:endDateLength -7]];
cell.titleLabel.text = aStage.title;
cell.dateLabel.text = dateTitle;
cell.nameLabel.text = aStage.teacher;
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 60;
}
#pragma mark -
#pragma mark Table view selection
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//When a row is selected, create the detail view controller and set its detail item to the item associated with the selected row.
DetailViewController *detailViewController = [[DetailViewController alloc] initWithStyle:UITableViewStyleGrouped];
Month *aMonth = [appDelegate.stages objectAtIndex:indexPath.section];
detailViewController.stage = [aMonth.stagesPerMonth objectAtIndex:indexPath.row];
// Push the detail view controller.
[[self navigationController] pushViewController:detailViewController animated:YES];
[detailViewController release];
}
#pragma mark -
#pragma mark Memory management
- (void)dealloc
{
[appDelegate release];
[super dealloc];
}
#end
If you want to use the standard activity indicator in the status bar call:
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
Just before you call the parser.
Then once the parser is complete (the didEndDocument method), call:
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
I'm not going to write the code for you, but here are some steps you could take.
1. For a better UX, add the RootViewController.view to the window before you start the xml parsing.
2. In your RootViewController: viewDidLoad method, create and display a UIActivityIndicatorView (a "spinner").
3. When your parsing is done, call a method on the RootViewController that does 3 things:
a) hides the spinner
b) loads the tableView's data source (aMonth.stagesPerMonth)
c) tableView[reloadData];
Good luck.
-Mike