title: Core Data in Swift: Comparing objects in a for loop
body: <p>I'm trying to update the user's music listen history by checking to see if any <code>MPMediaItemPropertyPlayCount</code>s have changed since the last check. Right now, upon each check, I'm querying the entire iPod library and comparing their existing play counts already in Core Data. If current play count != play count stored in Core Data, we do something with that song, since we know the user has listened to it recently.</p>
  
  <p>In my code, <strong>I'm struggling to loop through all iPod songs <em>and</em> search for corresponding Core Data objects simultaneously.</strong> The code below prints out way too many lines. How do I search for objects in Core Data in a <code>for</code> loop?</p>
  
  <pre><code>class func checkiPodSongsForUpdate() {
  
          var appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
  
          var context: NSManagedObjectContext = appDel.managedObjectContext!
  
          var newSong = NSEntityDescription.insertNewObjectForEntityForName("IPodSongs", inManagedObjectContext: context) as! NSManagedObject
  
          var request = NSFetchRequest(entityName: "IPodSongs")
  
          request.returnsObjectsAsFaults = false
  
          var results = context.executeFetchRequest(request, error: nil)
  
  
          let query = MPMediaQuery.songsQuery()
  
          let queryResult = query.collections as! [MPMediaItemCollection]
  
          for song in queryResult {
  
              for song in song.items as! [MPMediaItem] {
  
                  request.predicate = NSPredicate(format: "title = %@", "\(song.valueForProperty(MPMediaItemPropertyTitle))")
  
                  for result: AnyObject in results! {
  
                      if let playCount = result.valueForKey("playCount") as? String {
  
                          if playCount != "\(song.valueForProperty(MPMediaItemPropertyPlayCount))" {
  
                              println("\(song.valueForProperty(MPMediaItemPropertyTitle)) has a new play count.")
  
                          } else {
  
                              println("User hasn't listened to this song since last check.")
                          }
                      }
                  }
              }
          }
      }
  </code></pre>