Objective-C使用NSDictionary实例填充表视图

时间:2011-02-14 18:53:20

标签: objective-c xml macos nsdictionary nstableview

我需要一些帮助我想将xml文件加载到表视图中这是我到目前为止,有人可以向我解释如何执行此操作。我认为它也会涉及绑定,我对此有所了解。

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

谢谢,萨米。

1 个答案:

答案 0 :(得分: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中的表数据源。