【问题标题】:Objective-C Populating a table view with an instance of NSDictionaryObjective-C 使用 NSDictionary 的实例填充表视图
【发布时间】:2011-02-14 18:53:19
【问题描述】:

我需要一些帮助,我想将 xml 文件加载到表格视图中,这是我目前所拥有的,谁能向我解释如何做到这一点。我认为它也会涉及绑定,我对此有所了解。

NSString* libraryPath = @"~/Music/iTunes/iTunes Music Library.xml";
NSDictionary* musicLibrary = [ NSDictionary dictionaryWithContentsOfFile: libraryPath ];

谢谢,萨米。

【问题讨论】:

    标签: objective-c xml macos nsdictionary nstableview


    【解决方案1】:

    您可以使用 NSXMLDocument 来解析 XML 文件,这可能比实现 NSXMLParser. 更容易一些。这是一个示例(未经测试)。

    - (void) parseItunesLibrary {
        NSError* error = nil;
        NSString* libraryPath = nil;
    
        // better way to get the iTunes database file (in case library was moved)
        NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
        NSDictionary* iAppsDict = [defaults persistentDomainForName:@"com.apple.iApps"];
        NSArray* itunesDBPath = [iAppsDict objectForKey:@"iTunesRecentDatabasePaths"];
        if( [itunesDBPath count] > 0 ) {
            libraryPath = [[itunesDBPath objectAtIndex: 0] stringByExpandingTildeInPath];
        }   
    
        NSData* libraryData = [NSData dataWithContentsOfFile:libraryPath];
        NSXMLDocument* libraryDoc = [[NSXMLDocument alloc] initWithData:libraryData options:NSXMLDocumentTidyXML error:&error];
        // handle error before continuing here
        if (error) {
            NSLog(@"%@", [error localizedDescription]);
            [libraryDoc release];
            return;
        }
    
        NSXMLElement* root = [libraryDoc rootElement];
        [libraryDoc release];
    
        // assuming you wanted an array of the songs you can get them like this
        NSArray* songsArray = [root nodesForXPath:@".//dict/dict/dict" error:nil];
    
       // to access the different song elements you can do something like this
        for(NSXMLElement* song in songsArray) {
            NSString* songArtist = [[[song nodesForXPath:@"./Artist" error:nil] lastObject] stringValue];
        }
    }
    

    一旦你有了这些数据,你可以用任何你喜欢的方式把它放在NSTableView 中。在NSTableView Programming Guide 中查看使用表数据源。

    【讨论】:

    • 嗯,我不记得了,哈哈,但我确实实现了类似的东西。除了潜在的语法错误之外,这应该仍然有效。
    猜你喜欢
    • 1970-01-01
    • 2010-12-18
    • 2012-05-05
    • 2014-08-23
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    相关资源
    最近更新 更多