0

为什么以下结果会导致tableview充满“Artist”而不是充满实际艺术家名称的tableview?我哪里做错了?我如何从集合中拉取艺术家的价值?所有的帮助表示赞赏...如何从MPMediaItemCollection中拉取艺术家值

var tableData = MPMediaQuery.artistsQuery() 

override func viewDidLoad() { 
    super.viewDidLoad() 
    self.artistTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") 
    tableData.groupingType = MPMediaGrouping.Artist 
} 

func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return 1 
} 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return self.tableData.collections!.count 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell  { 
    let cell: UITableViewCell = self.artistTableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell 
    let artist: MPMediaItemCollection = tableData.collections![indexPath.row] 

    if artist.valueForProperty(MPMediaItemPropertyArtist) == nil { 
     cell.textLabel?.text = "Artist" as String 
    } else { 
    let artistName = artist.valueForProperty(MPMediaItemPropertyArtist) as! NSString 
    cell.textLabel?.text = artistName as String 
    } 
    return cell 
} 

回答

1

你可以通过它的representativeItem访问MPMediaItemCollection的属性。你取艺术家的名字,像这样:

let artist : MPMediaItemCollection = tableData.collections![indexPath.row] 
let artistName = artist.representativeItem.artist ?? "Unknown Artist" 

虽然如果我是你,我不会强行拆开包装tableData.collections因为如果你的用户有一个空的iTunes资料库中行将情况下应用程序崩溃。

+0

这工作......谢谢! – rocketman240

+0

xcode迫使我做类似(tableData.collections?)的事情!这是更好吗? – rocketman240

+0

@ rocketman240你想使用可选的绑定或者使用'guard'检查以确保'tableData.collections'不是零。例如'如果let collections = tableData.collections {//继续前面的操作}'或'guard let collections = tableData.collections else {// handle else}' – Wes

相关问题