1

我正在尝试解析一个 XML 文件TBXML并将这些值放入多维NSMutableArray 中,但问题是这些值没有被添加到数组中,如果我输出这些值,那么它会返回nulland 0

这是我的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self downloadAndParseXml:@"http://www.w3schools.com/XML/note.xml"];

    // RETURNS 0
    NSLog(@"weatherArray count: %d", [weatherArray count]);

    // RETURNS NULL
    NSLog(@"weatherArray value: %@", weatherArray[0][0]);
}

- (void)downloadAndParseXml:(NSString *)xmlUrl
{
    // Allocating the array
    weatherArray = [NSMutableArray array];

    TBXMLSuccessBlock sBlock = ^(TBXML *tbxmlDocument) {
        if (tbxmlDocument.rootXMLElement)
            [self fillArrayWithXmlContents:tbxmlDocument.rootXMLElement];
    };

    TBXMLFailureBlock fBlock = ^(TBXML *tbxmlDocument, NSError *error) {
        NSLog(@"Failureblock: %@\n%@", [error localizedDescription], [error userInfo]);
    };

    [TBXML newTBXMLWithURL:[NSURL URLWithString:xmlUrl] success:sBlock failure:fBlock];
}

- (void)fillArrayWithXmlContents:(TBXMLElement *)element {
    do {
        if (element->firstChild)
            [self fillArrayWithXmlContents:element->firstChild];

        if ([[TBXML elementName:element] isEqualToString:@"note"]) {

            // Adding values into the multidimensional array
            [weatherArray addObject:[NSArray arrayWithObjects:
                [TBXML textForElement:[TBXML childElementNamed:@"to" parentElement:element]],
                [TBXML textForElement:[TBXML childElementNamed:@"from" parentElement:element]],
                [TBXML textForElement:[TBXML childElementNamed:@"heading" parentElement:element]],
                [TBXML textForElement:[TBXML childElementNamed:@"body" parentElement:element]], NULL]];

            // Correct value is getting logged
            NSLog(@"weatherArray value: %@", weatherArray[0][0]);
        }
    } while ((element = element->nextSibling));
}
4

1 回答 1

1

可能您需要做的是等待该过程完成并且该块实际上不知道您在其中做什么,或者我会说内部函数未被块捕获。所以使用数组(调用函数仅在块完成后才使用您的数组)。

例子:

TBXMLSuccessBlock s = ^(TBXML *tbxml) {
    NSLog(@"yes");
    // Do something with TBXML object "tbxml/add it ur array
   //Here you call the function which is about to use your array.

};

//Not outside the block.

编辑:参考this==>实现API时如何避免在块中捕获自我?

于 2013-08-29T07:52:11.340 回答