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

How to assign string to NSDictionary using for loop?

所以,我在我的应用程序上使用 mpmediapicker 检索歌曲信息。我想将歌曲信息分配给字典,以便很容易将其填充到表格视图中。但是我在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;})

我该怎么做?

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

试试这个:

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]]()

如果我没记错歌单是NSDictionary

您必须创建一个 NSMutableArray

var playlistArray : NSMutableArray = []

现在将 playlist 添加到 for 循环内的数组中。

playlistArray.addObject(playlist)

循环完成后打印

println("\(playlistArray)")