Sharing when reading an array from CoreData
When I try to access my array that is being populated with data from CoreData. I am getting EXC_BAD_ACCESS error.
Here is my code:
var endPointList: Array<SettingsModel> = []
override func viewDidLoad() {
var context = getManagedObjectContext()
let fetchRequest = NSFetchRequest(entityName: "SettingsEndpoint")
endPointList = context.executeFetchRequest(fetchRequest, error: nil) as [SettingsModel]
}
I am getting an error when I click a button that launches the following IBAction:
@IBAction func showEndPointAlert(){
let alertController = UIAlertController(title: "Endpunkte Auswahl", message: "WΓ€hlen sie einen Endpunkt", preferredStyle: .Alert)
for endPoint : SettingsModel in endPointList {
var endPointNameFromData:String = endPoint.name as String
}
let cancelAction = UIAlertAction(title: "Abbrechen", style: .Cancel) { (_) in }
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion:nil );
}
The debugger points to the following line:
var endPointNameFromData:String = endPoint.name as String
Strangely, if I execute this code inside the viewDidLoad () method, it runs. Why is this?
UPDATE:
Now with some changes from Mundi. I am getting a slightly different error:
2015-01-06 12:18:21.818 ShareExtension[1056:20857]
-[SettingsModel name]: unrecognized selector sent to instance 0x6080000b2fc0
2015-01-06 12:20:24.755 ShareExtension[1056:20857]
*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '
-[SettingsModel name]: unrecognized selector sent to instance 0x6080000b2fc0'
My settingsModel class:
import UIKit
import CoreData
@objc(SettingsModel)
class SettingsModel: NSManagedObject {
@NSManaged var name:String
@NSManaged var webservice:String
@NSManaged var service:String
}
source to share
When extracting from Core Data, you usually need to type the result into the correct type. Simply declaring a variable of a specific type is not enough.
It is preferable not to use AnyObject
but the corresponding NSManagedObject
subclass.
endPointList = context.executeFetchRequest(fetchRequest, error: nil) as [EndPoint]
for endPoint : EndPoint in endPointList {
println(endpoint.name)
}
source to share