iphone - NSMutableArray 不获取 XML 值

标签 iphone ios objective-c xml tbxml

我正在尝试使用 TBXML 解析 XML 文件并将值放入多维 NSMutableArray 但问题是这些值没有被添加到数组中,如果我输出这些值然后它返回 null0

这是我的代码:

- (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));
}

最佳答案

可能你需要做的是等待进程完成,而 block 实际上不知道你在里面做了什么,或者我会说内部函数没有被 block 捕获。所以使用数组(仅在 block 完成后调用正在使用您的数组的函数。

示例:

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.

编辑:引用这个==> How do I avoid capturing self in blocks when implementing an API?

关于iphone - NSMutableArray 不获取 XML 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18504999/

相关文章:

ios - 设置主 TableView 行的动态高度,该行有另一个从 TableView ?

ios - While Loop in Swift 需要声明?

ios - UITableViewCell 滚动时弯曲动画

iphone - 如何使用 iPhone SDK 为这样的图像制作动画?

ios - AVAudioPlayer 不播放音频

ios - 将新用户对象的读/写访问权限限制为仅该用户?

iphone - 适用于 iOS 和 Android NDK 的 C++ 日志记录框架

iphone - iPhone 应用程序的本地存储

ios - 自定义 UITableView 单元格导致错误

c# - iOS Row Selected 未被调用