Michael Md Di Pietro
Michael Md Di Pietro

Reputation: 71

XML Parsing and set variables to instance

I created a class called "event". This class has three variables.

Main file initialize an instance of this class, after I parse an xml file but when I go to retrieve the created instance I did not recognize.

Where am I wrong?

#import "mkViewController.h"
#import "evento.h"

@interface mkViewController ()    
@end

@implementation mkViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSURL *url = [NSURL URLWithString:@"http://xxxxx.it/xxx.xml"];
    parser = [[NSXMLParser alloc] initWithContentsOfURL:url];

    [parser setDelegate:self];
    [parser setShouldResolveExternalEntities:NO];
    [parser parse];

    NSMutableArray *datiEvento = [NSMutableArray array];
    evento *eventoTrovato = [[evento init]alloc];
}

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

    if ([element isEqualToString:@"evento"]) {        
        // Create la array dell'evento
        eventoTrovato.nome = string;  **<--- not found eventoTrovato instace**
    }    
}

Upvotes: 0

Views: 92

Answers (1)

kabarga
kabarga

Reputation: 803

You created only local variable eventoTrovato in viewDidLoad. If you want to use it not only in one method then you have to define the variable or property in your class, like:

@interface mkViewController ()    
@property (nonatomic, strong) evento *eventoTrovato;
@end

.....

- (void)viewDidLoad
{
    ....... 
    self.eventoTrovato = [evento new];
}

- (void)parser.........
{            
     .......
     _eventoTrovato.nome = string;  
}

Another thing is if you want to store many elements into array. The code will looks like:

@interface mkViewController ()    
@property (nonatomic, strong) NSMutableArray *datiEvento;
@end

- (void)viewDidLoad
{
    ....... 
    self.datiEvento = [NSMutableArray array];
}

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

    if ([element isEqualToString:@"evento"]) {  
        evento *eventoTrovato = [evento new];      
        eventoTrovato.nome = string;

        [self.datiEvento addObject:eventoTrovato];
    }    
}

Upvotes: 0

Related Questions