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

标签 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=

请帮助我的 friend 提前致谢

最佳答案

rssOutputData = [[NSMutableArray alloc] init]; 移动到模型/类的 viewDidLoadinit

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

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

关于ios - Objective-C:for循环没有执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20611943/

相关文章:

iphone - 如何在Google Maps iOS上绘制优化路线?

ios - 无法识别的选择器发送到实例,将按钮连接到 View Controller 后出现 Storyboard 错误

ios - 带有 XCode 4 的 MPVolumeView( Storyboard)

iphone - 即使没有有效的内存泄漏,我的应用程序也会收到内存警告

iphone - UITableViewCells 周围的黑角

ios - 如何为依赖于使用 cocoapods 添加的其他框架的所有体系结构构建 cocoa touch 框架?

ios - 如何在 Objective-C 中旋转 UIButton 和 UILabel 的文本?

ios - SKSpriteNode 不稳定滑动?

iphone - 使用NSUserDefaults检测应用程序的初始启动

ios - 使用 ASIS3 启用 HTTPS