通过 AppleScript 获取独特的 iTunes 艺术家列表

Get list of unique iTunes artists via AppleScript

我正在尝试从我的资料库中获取独特的 iTunes 艺术家和流派列表。 AppleScript 的某些操作可能会很慢,在这种情况下我不能在速度上做出太多妥协。我可以对我的代码做任何进一步的重构吗?

tell application "iTunes"
    -- Get all tracks
    set all_tracks to shared tracks

    -- Get all artists
    set all_artists to {}
    repeat with i from 1 to count items in all_tracks
        set current_track to item i of all_tracks
        set current_artist to genre of current_track
        if current_artist is not equal to "" and current_artist is not in all_artists then
            set end of all_artists to current_artist
        end if
    end repeat
    log all_artists
end tell

我觉得应该有一种更简单的方法来从 iTunes 中获取我不知道的艺术家或流派列表...

如果您获得 属性 值列表而不是跟踪对象,例如

,您可以保存许多 Apple 事件
tell application "iTunes"
    -- Get all tracks
    tell shared tracks to set {all_genres, all_artists} to {genre, artist}
end tell

解析字符串列表完全不消耗 Apple 事件。

-- Get all artists
set uniqueArtists to {}
repeat with i from 1 to count items in all_artists
    set currentArtist to item i of all_artists
    if currentArtist is not equal to "" and currentArtist is not in uniqueArtists then
        set end of uniqueArtists to currentArtist
    end if
end repeat
log uniqueArtists

在 Cocoa (AppleScriptObjC) 的帮助下,它可能要快得多。 NSSet 是包含唯一对象的集合类型。从数组创建集合时,所有重复项都会被隐式删除。 allObjects() 方法将集合变回数组。

use framework "Foundation"

tell application "iTunes" to set all_artists to artist of shared tracks
set uniqueArtists to (current application's NSSet's setWithArray:all_artists)'s allObjects() as list