开发者

How to display different values in different custom tableview cells through XML parsing in iPhone?

I have an application in which I have an XML based application. This is created to display the weather conditions for current day, tomorrow, day after tomorrow and day after day after tomorrow.

I have created a custom table view cell so that I can display these details which are parsed from XML into these cells. I have done all the code for parser and displaying it on controller but the problem is only one same value is displayed in each cell of tableview.

This is my code for element class:

#import <Foundation/Foundation.h>


@interface TWeatherElement : NSObject 
{
    NSString *mIcon;
    //NSString *mForecastdate;
    NSString *mCurrentdate;
    NSString *mConditionname;
    NSString *mMintemp;
    NSString *mMaxtemp;
    NSString *mWind;
    NSString *mHumidity;
    NSString *mWeather;
    NSString *mXmlapireply;

 }

@property (nonatomic,retain) NSString *icon;
//@property (nonatomic,retain) NSString *forecastdate;
@property (nonatomic, retain)NSString *currentdate;
@property (nonatomic,retain)NSString *conditionname;
@property (nonatomic,retain)NSString *mintemp;
@property (nonatomic, retain)NSString *maxtemp;
@property (nonatomic, retain)NSString *wind;
@property (nonatomic, retain)NSString *humidity;
@property (nonatomic, retain)NSString *weather;
@property (nonatomic, retain)NSString *xmlapireply;


@end

and the .m

#import "TWeatherElement.h"


@implementation TWeatherElement
@synthesize icon = mIcon;
//@synthesize forecastdate = mForecastdate;
@synthesize currentdate = mCurrentdate;
@synthesize conditionname = mConditionname;
@synthesize mintemp = mMintemp;
@synthesize maxtemp = mMaxtemp;
@synthesize wind = mWind;
@synthesize humidity = mHumidity;
@synthesize weather = mWeather;
@synthesize xmlapireply =mXmlapireply;


-(void)dealloc
{
    [mIcon release];
    //[mForecastdate release];
    [mCurrentdate release];
    [mConditionname release];
    [mMintemp release];
    [mMaxtemp release];
    [mWind release];
    [mHumidity release];
    [mWeather release];
    [mXmlapireply release];
    [super dealloc];
}


@end

This is my parser class:

#import "TWeatherElement.h"//this is the class where the elements are Created
#import <Foundation/Foundation.h>


@interface TWeatherParser : NSObject<NSXMLParserDelegate> 
{
    NSString *urlString;

    NSMutableArray *mParserArray;
    //NSXMLParser *mXmlParser;
    NSXMLParser *parser;
    NSMutableString *mCurrentElement;
    BOOL elementFound;
    TWeatherElement *mWeather;

}
@property (nonatomic, retain) NSString *urlString;
//@property (nonatomic, retain) NSMutableArray *tweetArray;
//
@property (nonatomic, retain) NSXMLParser *parser;
@property (nonatomic, retain) NSMutableString *currentElement;
@property (nonatomic, retain)NSMutableArray *mParserArray;
@property (nonatomic, retain) TWeatherElement *weatherobj;

//-(void)getInitialiseWithData:(NSData *)inData;
-(NSMutableArray *)retrieveTweetsFromURL:(NSString *)urlString;
@end





#import "TWeatherParser.h"
#import "JourneyAppDelegate.h"
#import "api.h"
//#define kParsingFinishedNotification @"ParsingFinishedNotification"


@implementation TWeatherParser
@synthesize weatherobj = mWeather;
@synthesize currentElement = mCurrentElement;
@synthesize mParserArray;
@synthesize urlString;
@synthesize parser;


-(id)init
{
    if ((self = [super init]))
    {
        self.mParserArray = [[[NSMutableArray alloc]init]autorelease];
    }
    return self;
}


-(NSMutableArray *)retrieveTweetsFromURL:(NSString *)urlString {

    mParserArray = [[NSMutableArray alloc] init];


    NSURL *urlToRetrieve = [NSURL URLWithString:urlString] ;

    parser = [[NSXMLParser alloc] initWithContentsOfURL:urlToRetrieve];

    [parser setDelegate:self];

    if ([parser parse])
    {
        NSLog(@"Parsed OK");

    } else {
        NSLog(@"There's been a problem :-(");
    }

    return mParserArray;

}



-(void)parser:(NSXMLParser *)parser didStartElement:(NSString*) elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString*)qualifiedName attributes:(NSDictionary*)attributeDict
{

    if ([elementName isEqualToString:@"xml_api_reply"])
    {
        mWeather = [[TWeatherElement alloc]init];
        NSString *data8= [attributeDict objectForKey:@"version"];
        if(data8 !=nil)
            mWeather.xmlapireply =data8 ;
        [mParserArray addObject:mWeather];
    }
    if ([elementName isEqualToString:@"weather"])
    {
        NSString *data0= [attributeDict objectForKey:@"module_id"];
        if(data0 !=nil)
         self.weatherobj.weather=data0 ;
        [mParserArray addObject:self.weatherobj];
        NSLog(@"weather==%@",[attributeDict valueForKey:@"module_id"]);
    }
    if([elementName isEqualToString:@"current_date_time"])
    {
        NSString *data1= [attributeDict objectForKey:@"data"];
        if (data1 !=nil) 
            self.weatherobj.currentdate =data1;
        [mParserArray addObject:self.weatherobj];
        NSLog(@"current_date_time==%@",[attributeDict valueForKey:@"data"]);
    }
    if([elementName isEqualToString:@"condition"])
    {
        NSString *data2= [attributeDict objectForKey:@"data"];
        if (data2 !=nil) 
            self.weatherobj.conditionname=data2;
        [mParserArray addObject:self.weatherobj];
        NSLog(@"condition==%@",[attributeDict valueForKey:@"data"]);

    }
    if([elementName isEqualToString:@"humidity"])
    {
        NSString *data3= [attributeDict objectForKey:@"data"];
        if (data3 !=nil) 
            self.weatherobj.humidity =data3;
        [mParserArray addObject:self.weatherobj];
        NSLog(@"humidity==%@",[attributeDict valueForKey:@"data"]);

    }
    if([elementName isEqualToString:@"icon"])
    {
        NSString *data4= [attributeDict objectForKey:@"data"];
        if (data4 !=nil) 
            self.weatherobj.icon =data4;
        [mParserArray addObject:self.weatherobj];
        NSLog(@"icon==%@",[attributeDict valueForKey:@"data"]);

    }
    if([elementName isEqualToString:@"wind_condition"])
    {
        NSString *data5= [attributeDict objectForKey:@"data"];
        if (data5 !=nil) 
            self.weatherobj.wind =data5;
        [mParserArray addObject:self.weatherobj];
        NSLog(@"wind_condition==%@",[attributeDict valueForKey:@"data"]);
    }
    if([elementName isEqualToString:@"low"])
    {
        NSString *data6= [attributeDict 开发者_StackOverflow中文版objectForKey:@"data"];
        if (data6 !=nil)                   
            self.weatherobj.mintemp = data6;
        [mParserArray addObject:self.weatherobj];
        NSLog(@"low==%@",[attributeDict valueForKey:@"data"]);
    }
    if([elementName isEqualToString:@"high"])
    {
        NSString *data7= [attributeDict objectForKey:@"data"];
        if (data7 !=nil)                   
            self.weatherobj.maxtemp =data7; 
        [mParserArray addObject:self.weatherobj];
        NSLog(@"high==%@",[attributeDict valueForKey:@"data"]);
    }



}
-(void)parser:(NSXMLParser*)parser foundCharacters:(NSString*)string
{
    if (nil!= self.currentElement)
    {
        [self.currentElement appendString:string];
    }
}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qName
{
    if (nil != qName)
    {
        elementName  = qName;
    }
    if ([elementName isEqualToString:@"current_date_time "]) 
    {
        self.weatherobj.currentdate = self.currentElement;

    }
    else if ([elementName isEqualToString:@"condition "]) 
    {
        self.weatherobj.conditionname = self.currentElement;

    }
    else if ([elementName isEqualToString:@"humidity "]) 
    {
        self.weatherobj.humidity = self.currentElement;

    }
    else if ([elementName isEqualToString:@"icon "]) 
    {
        self.weatherobj.icon = self.currentElement;

    }
    else if ([elementName isEqualToString:@"wind_condition "]) 
    {
        self.weatherobj.wind = self.currentElement;

    }
    else if ([elementName isEqualToString:@"low "]) 
    {
        self.weatherobj.mintemp = self.currentElement;

    }
    else if ([elementName isEqualToString:@"high "]) 
    {
        self.weatherobj.maxtemp = self.currentElement;

    }
    else if ([elementName isEqualToString:@"weather"]) 
    {
        [mParserArray addObject:self.weatherobj];
        NSLog(@"mDataArray count = %d",[mParserArray count]);
        [self.weatherobj release];
        //[mParserArray release];
    }   
}



-(void)dealloc
{
    [super dealloc];
    self.weatherobj = nil;
    self.currentElement = nil;
}
@end

This is my controller class in which I am setting the array

#import <UIKit/UIKit.h>
#import "TWeatherParser.h"
@class TWeatherParser;


@interface TWeatherController : UITableViewController {

    UITableView *mTableView;
    NSMutableArray *mImage;
    NSMutableArray *weatherarray;
    TWeatherParser *weather;


}
@property (nonatomic, retain) IBOutlet UITableView *mTableView;
@property (nonatomic, retain) NSMutableArray *weatherarray;
@property (nonatomic, retain) TWeatherParser *weather;

@end





#import "TWeatherController.h"
#import "TWeatherCell.h"
#import "TWeatherElement.h"
#import "TWeatherParser.h"
//#import "api.h"



@implementation TWeatherController
@synthesize mTableView;
@synthesize weatherarray;
@synthesize weather;


#pragma mark -
#pragma mark Initialization

- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    style = UITableViewStyleGrouped;
    if (self = [super initWithStyle:style]) {
    }
    return self;
}



#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];

    NSLog(@"About to run the ViewDidLoad superclass method...");
    [super viewDidLoad];

    self.title = @"Everyone";

    self.editButtonItem.possibleTitles = [NSSet setWithObjects:@"Add/Edit", @"Done", nil];

    self.editButtonItem.title = @"Update";

    weatherarray = [[NSMutableArray alloc] init];


    TWeatherParser *xmlController;
    xmlController = [[TWeatherParser alloc] init];

    // Now go and grab the data from the url... 

    weatherarray = [xmlController retrieveTweetsFromURL:kXMLurl];

    NSLog(@"\n\nThere are %d objects in the array...", [weatherarray count]);

    [xmlController release];

}




#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [weatherarray count];

}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";


   TWeatherCell *cell =(TWeatherCell *) [mTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[TWeatherCell alloc] initWithStyle:UITableViewStyleGrouped reuseIdentifier:CellIdentifier] autorelease];
    }
    TWeatherElement *newobj = [weatherarray objectAtIndex:indexPath.row];
    if ([newobj.icon isEqualToString:@"http://\n"])
    {
        cell.weatherimage.image = [UIImage imageNamed:@"listIcon-H.png"];
    }
    else {
        NSData *imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:newobj.icon]];
        cell.weatherimage.image = [UIImage imageWithData:imageData];
        [imageData release];
    }
//Here it is creating some problem here same value is getting displayed for every cells.
    cell.reportdate.text = newobj.currentdate;
    cell.conditionname.text = newobj.conditionname;
    cell.twotemp.text = [NSString stringWithFormat:@"Temp:%@/%@",newobj.mintemp,newobj.maxtemp];
    cell.twodirection.text = newobj.wind;
    cell.humidity.text = newobj.humidity;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    // Configure the cell...

    return cell;
}



- (void)dealloc {
    [super dealloc];
    [weatherarray release];
    [weather release];
    [mTableView release];
}


@end


Try this

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
        //tableViewDataSource should contain your data returned from parsing
        //Here put a NSLog to print the Array Count just know you are getting right values 
    return [tableViewDataSource count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
     UICustomTableViewCell *cell;
        cell = [tableView dequeueReusableCellWithIdentifier:@"cell"]; //Create cell
    if(cell == nil)
    {
        cell = [[[UICustomTableViewCell alloc] init] autorelease];
        // Initialize All controls here if you want to
        //This If statement will execute (Number of visible Cells) number of times
    }
    else
    {
        // when Reused get the controls here
    }
    // Assign the data here
    cell.customlabel.text =[tableDataSourceArray objectAtIndex:indexPath.row];

    return cell;
}

Just let me know if you have a problem.


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
   static NSString *CellIdentifier = @"Cell";

  ListDetailCell *cell= [[[ListDetailCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];

tableView.backgroundColor = [UIColor whiteColor];

 if (cell == nil) 
 {
  cell = [[[ListDetailCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier]
        autorelease];
  }

 switch (indexPath.row)
{
case 0:
    NSLog(@"%d",indexPath.row);
    cell.leadingLabel.text = @"Name: ";
    cell.leadingLabel.font = [UIFont fontWithName:LABELS_FONT_NAME_BOLD size:11.0f];
    cell.leadingLabel.textColor = FONT_GREEN_COLOR;

    cell.volInfo.text = volRow.volName;
    cell.volInfo.font = [UIFont fontWithName:LABELS_FONT_NAME size:11.0f];
    break;
case 1:
    NSLog(@"%d",indexPath.row);
    cell.leadingLabel.text = @"Address: ";
    cell.leadingLabel.font = [UIFont fontWithName:LABELS_FONT_NAME_BOLD size:11.0f];
    cell.leadingLabel.textColor = FONT_GREEN_COLOR;

    cell.volInfo.text = volRow.volAddress;
    cell.volInfo.font = [UIFont fontWithName:LABELS_FONT_NAME size:11.0f];
    break;
case 2:
    NSLog(@"%d",indexPath.row);
    cell.leadingLabel.text = @"Phone: ";
    cell.leadingLabel.font = [UIFont fontWithName:LABELS_FONT_NAME_BOLD size:11.0f];
    cell.leadingLabel.textColor = FONT_GREEN_COLOR;

    cell.volInfo.text = volRow.phone;
    cell.volInfo.font = [UIFont fontWithName:LABELS_FONT_NAME size:11.0f];
    break;
case 3:
    NSLog(@"%d",indexPath.row);
    cell.leadingLabel.text = @"Email: ";
    cell.leadingLabel.font = [UIFont fontWithName:LABELS_FONT_NAME_BOLD size:11.0f];
    cell.leadingLabel.textColor = FONT_GREEN_COLOR;

    cell.volInfo.text = volRow.email;
    cell.volInfo.font = [UIFont fontWithName:LABELS_FONT_NAME size:11.0f];
    break;

default:
    NSLog(@"Out of Range ",indexPath.row);
    break;
}

return cell;
}

If you want to show different values in different cell then you have to use switch case to detect row index :

the volRow variable holds your parsed data that is to be displayed...


Apple's SeismicXML does exacly that and is easy to adapt.

http://developer.apple.com/library/ios/#samplecode/SeismicXML/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜