Shyam Shyam - 5 months ago 17
Swift Question

managedObjectContext cannot be used more than once?

I have an app which uses CoreData to save different playlists using

. After saving the first one, while I try to add the second one, the app crashes. Below is the entire debug queue.

Creation of the first record.

musicTemp = <MPMediaItemCollection: 0x13df04440>=========>prepareForSegue
▿ Optional<NSManagedObjectContext>
- Some : <NSManagedObjectContext: 0x13de88a60>

musicTemp = <MPMediaItemCollection: 0x13df04440>=========>saveValues
Optional(<NSManagedObjectContext: 0x13de88a60>)
Number of rows = 1
Number of rows = 1
musicTemp = <MPMediaItemCollection: 0x13df04440>=========>RuleViewCell

End of first record creation. Start of second record creation,

musicTemp = <MPMediaItemCollection: 0x13dea7620>=========>prepareForSegue
▿ Optional<NSManagedObjectContext>
- Some : <NSManagedObjectContext: 0x13de88a60>

musicTemp = <MPMediaItemCollection: 0x13dea7620>=========>saveValues
Optional(<NSManagedObjectContext: 0x13de88a60>)
2016-09-10 11:39:02.469 AppName[5237:2139350] -[MPMediaItemCollection compare:]: unrecognized selector sent to instance 0x13df04440
All Exceptions
error: use of undeclared identifier 'mainManagedObjectContext'
error: 1 errors parsing expression

App Crashes!!

The related code which does the addition of records,

// Method to save the extracted values to CoreData Objects
private func saveValues() {

// Initialize entity description
let RuleDescription = NSEntityDescription.entityForName("Rule",inManagedObjectContext:mainManagedObjectContext!)
let rule = Rule(entity: RuleDescription!, insertIntoManagedObjectContext: mainManagedObjectContext)
// Set object values from temporary variables = musicTemp!
print("musicTemp = \(musicTemp!.count)=========>saveValues")
// Save the object in privateManagedObjectContext
if ((mainManagedObjectContext?.hasChanges) != nil) {
do {
try mainManagedObjectContext?.save()
} catch let saveError as NSError {
print("(AddRuleViewController)(mainManagedObjectContext)saveError: \(saveError), \(saveError.userInfo)")

is referenced using dependency injection. I am not able to figure out why it is able to save the first time, but not again. Actually, it complains about


There appears to be something strange with your musicTemp variable.

You are hard casting it (which is usually a code smell) and the error is around that variable and the object that it really contains.

The indicator is:

-[MPMediaItemCollection compare:]: unrecognized selector sent to instance 0x14ef90390

Core Data is trying to call compare: on the MPMediaItemCollection object but 0x14ef90390 is not a MPMediaItemCollection.

Start poking at that variable and make sure it really is what you think it is.