如何在iphone中的tableview单元格中存储xml值并计入数组和显示值

时间:2011-05-30 05:26:46

标签: iphone objective-c xml

嗨朋友,感谢我从xml获取的数据和结果我可以在我的控制台中看到我在控制台中看到的所有元素值,但我的问题在我的NSLog中(@“mDataArray count =%d”,[mParserArray count]); 我在mdataarray中看不到任何计数值 这是我的解析器代码,请面试一下,告诉我我在解析器代码中做了什么错误

请面对我创建的类解析器和控制器类,并帮助我的朋友 这是我的parser.h文件----------------- /

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


@interface TWeatherParser : NSObject<NSXMLParserDelegate> 
{
    NSMutableArray *mParserArray;
    NSXMLParser *mXmlParser;
    NSMutableString *mCurrentElement;
    BOOL elementFound;
    TWeatherElement *mWeather;

}
@property (nonatomic, retain) NSMutableString *currentElement;
@property (nonatomic, retain)NSMutableArray *mParserArray;
@property (nonatomic, retain) TWeatherElement *weatherobj;

-(void)getInitialiseWithData:(NSData *)inData;

@end



this is mu parser.mfile---------------------------/


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


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

//-(id)init
//{
//  if ([super init]) 
//  {
//      currentElement release=[[NSMutableString alloc]init];
//      mWeather =nil;
//
//  }
//  return self;
//}

-(void)getInitialiseWithData:(NSData *)inData
{
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:inData];
    [parser setDelegate:self];
    [parser setShouldProcessNamespaces:YES];   //YES if the receiver should report the namespace and qualified name of each element, NO otherwise. The default value is NO
    [parser setShouldReportNamespacePrefixes:YES]; //YES if the receiver should report the scope of namespace declarations, NO otherwise. The default value is NO.
    [parser setShouldResolveExternalEntities:NO];//YES if the receiver should report declarations of external entities, NO otherwise. The default value is NO

    [parser parse];
    NSLog(@"%@",parser);

    [parser release];
}



-(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:data8];
    }
    if ([elementName isEqualToString:@"weather"])
    {
        NSString *data0= [attributeDict objectForKey:@"module_id"];
        if(data0 !=nil)
            mWeather.weather =data0 ;
        NSLog(@"weather==%@",[attributeDict valueForKey:@"module_id"]);
    }
     if([elementName isEqualToString:@"current_date_time"])
     {
         NSString *data1= [attributeDict objectForKey:@"data"];
         if (data1 !=nil) 
             mWeather.currentdate =data1;
         NSLog(@"current_date_time==%@",[attributeDict valueForKey:@"data"]);
     }
            if([elementName isEqualToString:@"condition"])
            {
                NSString *data2= [attributeDict objectForKey:@"data"];
                if (data2 !=nil) 
                    mWeather.conditionname=data2;
                NSLog(@"condition==%@",[attributeDict valueForKey:@"data"]);

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

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

            }
            if([elementName isEqualToString:@"wind_condition "])
            {
                NSString *data5= [attributeDict objectForKey:@"data"];
                if (data5 !=nil) 
                    mWeather.wind =data5;
                NSLog(@"wind_condition==%@",[attributeDict valueForKey:@"data"]);
            }
            if([elementName isEqualToString:@"low "])
            {
                NSString *data6= [attributeDict objectForKey:@"data"];
                if (data6 !=nil) 
                    mWeather.mintemp = data6;
                NSLog(@"low==%@",[attributeDict valueForKey:@"data"]);
            }
            if([elementName isEqualToString:@"high "])
            {
                NSString *data7= [attributeDict objectForKey:@"data"];
                if (data7 !=nil) 
                    mWeather.maxtemp =data7;
                NSLog(@"high==%@",[attributeDict valueForKey:@"data"]);
            }
    //{
//      self.currentElement = [NSMutableString string];
//  }
//  else 
//  {
//      self.currentElement = nil;
//  }


}
-(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 "]) 
    {
        mWeather.currentdate = self.currentElement;

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

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

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

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

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

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

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

}   
}

//-(void)parserDidEndDocument:(NSXMLParser *)parser
//{
//  [[NSNotificationCenter defaultCenter ]postNotificationName:kParsingFinishedNotification object:mParserArray];
//}

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

and this is my controller class where i want to show all parser value in table view cell in iphone but it not working proper i think my code is not proper in controller class how i can show all data in controller class please help some one
this is TWeatherController.h-------------------------/

#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;


@end


this is TWeatherController .m----------------------/

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


@implementation TWeatherController
@synthesize mTableView;


#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];

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
*/


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    api *ap = [[api alloc]init];
    NSData *aData = [ap getBusXMLAtStop:@"1"];
    NSString *str = [[NSString alloc] initWithData:aData encoding:NSUTF8StringEncoding];

    //NSInteger value = [str intValue];
    if (str)
    {
        NSLog(@"this is success %@",ap.dataReply);
        TWeatherParser *parser = [[TWeatherParser alloc]init];
        [parser getInitialiseWithData:ap.dataReply];
        [parser release];


    }
    else 
    {
        UIAlertView *alertview = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"cannot fetch" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertview show];
        [alertview release];
    }


    [ap release];



}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

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


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    //TWeatherParser *parse = [[TWeatherParser alloc]init];
    //weatherarray = parse.mParserArray;
    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 = [weather.mParserArray 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];
    }
    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.reportdate.text = newobj.currentdate;


    //cell.reportdate.text =@"My journey";
//  cell.conditionname.text = @"raji";
//  cell.twotemp.text = @"pradeep"; 
//  cell.twodirection.text = @"harish";
//  cell.humidity.text =@"23";
//  cell.weatherimage.image = [UIImage imageNamed:@"listIcon-H.png"];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    // Configure the cell...

    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // Navigation logic may go here. Create and push another view controller.
    /*
    <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
    */
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *) indexPath
{
    return 100.0;


}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end

1 个答案:

答案 0 :(得分:0)

NSLog(@"this is success %@",ap.dataReply);
        TWeatherParser *parser = [[TWeatherParser alloc]init];
        [parser getInitialiseWithData:ap.dataReply];
        [parser release];

初始化你的mParserArray = [NSMutableArray array]; 在这里,您需要将解析后的数组存储到某个变量中。你没有这样做。从您的代码weatherarray是应该保存解析值的变量。 我希望这能指出你正确的方向。将self.weatherarray指向parser. mParserArray或使用您计划的内容。