Objective-C:for循环没有执行?

时间:2013-12-16 13:19:00

标签: ios iphone objective-c xml

我的任务是通过解析xml数据来做登录表单,即通过url发送用户名和密码并且必须解析xml,我从url成功解析了xml数据,现在问题是我无法从解析的xml中读取状态数据。 for循环没有被执行的地方。请帮我怎么做。 这是我的代码

#import "RTVersion1ViewController.h"

@interface RTVersion1ViewController ()

@end

@implementation RTVersion1ViewController
@synthesize user,pass,username,pass1,webData,stat,sessid;
-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
    if([elementName isEqualToString:@"root"]) {
        //Initialize the array.
        rssOutputData = [[NSMutableArray alloc] init];
    }
    else if([elementName isEqualToString:@"userDetails"]) {
        //Initialize the book.
        aLogin = [[Login alloc] init];
        //Extract the attribute here.
        aLogin.userId = [[attributeDict objectForKey:@"userId"] integerValue];
        NSLog(@"Reading id value :%d", aLogin.userId);
    }
    NSLog(@"Processing Element: %@", elementName);
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if(!nodecontent)
        nodecontent = [[NSMutableString alloc] initWithString:string];else
            [nodecontent appendString:string];
    NSLog(@"Processing Value: %@", nodecontent);
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    if([elementName isEqualToString:@"root"])
        return;
    if([elementName isEqualToString:@"userDetails"]) {
        [rssOutputData addObject:aLogin];
        [aLogin release];
        aLogin= nil;
    }
    else
        [aLogin setValue:nodecontent forKey:elementName];
    [nodecontent release];
    nodecontent = nil;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                                   initWithTarget:self
                                   action:@selector(dismissKeyboard)];

    [self.view addGestureRecognizer:tap];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    NSString *firstName = [defaults objectForKey:@"firstname"];
    NSString *lastName = [defaults objectForKey:@"lastname"];
    user.text = firstName;
    pass.text = lastName;
    // Do any additional setup after loading the view, typically from a nib.
}
-(void)viewDidAppear:(BOOL)animated {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    // check if user is alraidy Login
    if([defaults objectForKey:@"firstname"]!=nil  && [defaults objectForKey:@"lastname"]!=nil){
     [self performSegueWithIdentifier:@"login" sender:defaults];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dismissKeyboard {
    [user resignFirstResponder];
    [pass resignFirstResponder];
}

- (void)dealloc {
    [user release];
    [pass release];
    [super dealloc];
}
- (void) alertStatus:(NSString *)msg :(NSString *)title
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                        message:msg
                                                       delegate:self
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil, nil];    
    [alertView show];
}
- (IBAction)Submit:(id)sender {
    username =user.text;
    pass1 = pass.text;
    if([user.text isEqualToString:@"" ]|| [pass.text isEqualToString:@""])
    {
        [self alertStatus:@"Please enter both Username and Password" :@"Login Failed!"];
        //greeting.text = @"Input Your Value";
        [user resignFirstResponder];
        [pass resignFirstResponder];
        return;
    }
     NSLog(@"%@%@",username,pass1);
    NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",username,pass1];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    //NSURL *url = [NSURL URLWithString:@"http://192.168.1.164:8080/RestoreTogether/userProfile/verifyUserDetail1"];
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
    // [theRequest addRequestHeader:@"Content-Type" value:@"application/xml"];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setValue:@"application/xml" forHTTPHeaderField:@"Accept"];
    [theRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [theRequest setHTTPBody:postData];
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if( theConnection )
    {
        webData = [[NSMutableData data] retain];
        NSLog(@"%@",webData);
    }
   }
-(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
{
    [webData release];
    [connection release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    samplearray = [[NSMutableArray alloc]init];
    xmlParserObject = [[NSXMLParser alloc] initWithData:webData];
    [xmlParserObject setDelegate:self];
    [xmlParserObject parse];
    for (int i =0; i<[rssOutputData count]; i++) {
        Login *log = [rssOutputData objectAtIndex:i];
        sessid = log.userId;
        NSLog(@"%d",sessid);
        stat = log.status;
        NSLog(@"%@",stat);
        [samplearray addObject:log];
    }

    [connection release];

}

@end

这是不起作用的循环

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
        samplearray = [[NSMutableArray alloc]init];
        xmlParserObject = [[NSXMLParser alloc] initWithData:webData];
        [xmlParserObject setDelegate:self];
        [xmlParserObject parse];
        for (int i =0; i<[rssOutputData count]; i++) {
            Login *log = [rssOutputData objectAtIndex:i];
            sessid = log.userId;
            NSLog(@"%d",sessid);
            stat = log.status;
            NSLog(@"%@",stat);
            [samplearray addObject:log];
        }

        [connection release];

    }

这是控制台输出(解析的xml的输出):

2013-12-16 18:37:21.498 RTVersion1[3238:c07] u1@gmail.comu1
2013-12-16 18:37:21.501 RTVersion1[3238:c07] <>
2013-12-16 18:37:21.604 RTVersion1[3238:c07] Processing Element: root
2013-12-16 18:37:21.604 RTVersion1[3238:c07] Processing Element: userDetail
2013-12-16 18:37:21.604 RTVersion1[3238:c07] Processing Element: userId
2013-12-16 18:37:21.604 RTVersion1[3238:c07] Processing Value: 20
2013-12-16 18:37:21.605 RTVersion1[3238:c07] Processing Element: userFirstName
2013-12-16 18:37:21.605 RTVersion1[3238:c07] Processing Value: u1
2013-12-16 18:37:21.605 RTVersion1[3238:c07] Processing Element: userLastName
2013-12-16 18:37:21.605 RTVersion1[3238:c07] Processing Value: u
2013-12-16 18:37:21.605 RTVersion1[3238:c07] Processing Element: userUserType
2013-12-16 18:37:21.605 RTVersion1[3238:c07] Processing Value: INDIVIDUAL
2013-12-16 18:37:21.605 RTVersion1[3238:c07] Processing Element: userUserName
2013-12-16 18:37:21.606 RTVersion1[3238:c07] Processing Value: u1@gmail.com
2013-12-16 18:37:21.606 RTVersion1[3238:c07] Processing Element: status
2013-12-16 18:37:21.606 RTVersion1[3238:c07] Processing Value: true
2013-12-16 18:37:21.606 RTVersion1[3238:c07] Processing Element: sessionvalue
2013-12-16 18:37:21.606 RTVersion1[3238:c07] Processing Value: 1_MX40NDQ1OTU2Mn5-VGh1IERlYyAwNSAwMjo0NjozNCBQU1QgMjAxM34wLjc1MTEzNTV-
2013-12-16 18:37:21.606 RTVersion1[3238:c07] Processing Element: tokenvalue
2013-12-16 18:37:21.607 RTVersion1[3238:c07] Processing Value: T1==cGFydG5lcl9pZD00NDQ1OTU2MiZzZGtfdmVyc2lvbj10YnJ1YnktdGJyYi12MC45MS4yMDExLTAyLTE3JnNpZz1jYjhhMjZmODQxNGUyNWM4Yzc3OWU4YzE3MTQ5ZmI4ZmYyOWFiMDE2OnJvbGU9cHVibGlzaGVyJnNlc3Npb25faWQ9MV9NWDQwTkRRMU9UVTJNbjUtVkdoMUlFUmxZeUF3TlNBd01qbzBOam96TkNCUVUxUWdNakF4TTM0d0xqYzFNVEV6TlRWLSZjcmVhdGVfdGltZT0xMzg2MjQwNDM1Jm5vbmNlPTAuNTgzNzUzMzA4MzA2MTc3OSZleHBpcmVfdGltZT0xMzg4ODMyMjY5JmNvbm5lY3Rpb25fZGF0YT0=

请事先帮助我的朋友

3 个答案:

答案 0 :(得分:3)

rssOutputData = [[NSMutableArray alloc] init];移至您的模特/班级的viewDidLoadinit

您在委托中多次使用和分配,这是不正确的。

-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
    if([elementName isEqualToString:@"root"]) {
        //Initialize the array.
        rssOutputData = [[NSMutableArray alloc] init];

答案 1 :(得分:1)

因为[rssOutputData count]在启动时为零,所以在成功解析后它将获取数据。

您正在[xmlParserObject parse]之后放置循环。

[xmlParserObject parse];
        for (int i =0; i<[rssOutputData count]; i++) {

从解析器获取完整结果后放置循环。 所以把你的For循环放在didEndElement

里面
if([elementName isEqualToString:@"root"])
//Your for loop should be here,
        return;

答案 2 :(得分:0)

在你的xml中有“userDetail”标签,你在解析器中查找“userDetails”:didStartElement:method。我认为这是你的问题的原因,删除额外的“s”,你将获得登录项。