如何使用for循环将字符串分配给NSDictionary?

时间:2015-05-28 04:33:48

标签: ios iphone swift nsdictionary

所以,我在我的应用程序上使用mpmediapicker检索歌曲信息。我想将歌曲信息分配给字典,以便将其填充到tableview中。但是我在for循环中为字典赋值时遇到了麻烦。

这是我的代码:

for thisItem in mediaItemCollection!.items as! [MPMediaItem]{

        let itemUrl = thisItem.valueForProperty(MPMediaItemPropertyAssetURL)
            as? NSURL

        let itemTitle =
        thisItem.valueForProperty(MPMediaItemPropertyTitle)
            as? String

        let itemArtist =
        thisItem.valueForProperty(MPMediaItemPropertyArtist)
            as? String

        let itemArtwork =
        thisItem.valueForProperty(MPMediaItemPropertyArtwork)
            as? MPMediaItemArtwork


        playlist = ["title" : itemTitle! , "artist" : itemArtist!, "song_url" : itemUrl!]


    }

以下是我得到的:

Optional({
    artist = "ASKING ALEXANDRIA";
    "song_url" = "ipod-library://item/item.mp3?id=5357233978197423496";
    title = Alerion;
})

它只检索最后一首歌。我该如何解决这个问题?

我想要的格式如下:

Optional({artist = "ASKING ALEXANDRIA";"song_url" = "ipod-library://item/item.mp3?id=5357233978197423496";title = Alerion;}, {artist = "ASKING ALEXANDRIA";"song_url" = "ipod-library://item/item.mp3?id=5357239348197423496"; title = The Prophecy;}, {artist = "ASKING ALEXANDRIA";"song_url" = "ipod-library://item/item.mp3?id=53572339781974234123";title = Breathless;})

我该怎么做?

2 个答案:

答案 0 :(得分:1)

如果我没错,则播放列表为NSDictionary

您必须创建NSMutableArray

var playlistArray : NSMutableArray = []

现在将playlist添加到数组里面以进行循环。

playlistArray.addObject(playlist)

完成循环后打印

println("\(playlistArray)")

答案 1 :(得分:0)

您没有将新数据附加到数组,只是使数组等于值

试试这个:

playlist += ["title" : itemTitle! , "artist" : itemArtist!, "song_url" : itemUrl!]

playlist.append(["title" : itemTitle! , "artist" : itemArtist!, "song_url" : itemUrl!])

假设您的播放列表是一系列字典,可以创建如下:

var playlist : [Dictionary<String, Int>] = []

var playlist = [Dictionary<String, Int>]()

var playlist : [[String:Int]] = []

var playlist = [[String:Int]]()