2014-10-17 50 views
0

我創建了一個名爲「event」的類。這個類有三個變量。XML解析並將變量設置爲實例

主要文件初始化此類的一個實例後,我解析一個XML文件,但當我去檢索創建的實例,我不認識。

我在哪裏錯了?

#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** 
    }  
} 

回答

0

您在viewDidLoad中只創建了局部變量eventoTrovato。如果你想不僅在一個方法來使用它,那麼你必須定義變量或屬性在您的類,如:

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

..... 

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

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

,如果你想存儲許多元素融入到陣列的另一件事是。該代碼將如下所示:

@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]; 
    }  
} 
+0

非常感謝您的回答,但是每當它發現某個元素不總是覆蓋同一個實例時,就這樣做? 如果爲每個找到的元素創建一個新的事件對象並將其添加到數組的最後我? – 2014-10-18 13:50:49

+0

是的。我更新了答案。 – kabarga 2014-10-18 14:00:36

+0

但感謝所以eventoTrovato *對象不被覆蓋cn總是發現新的數據? 當我去調用後添加數組,我沒有發現許多元素都相等? – 2014-10-18 14:04:06