从CoreData读取数组时共享扩展崩溃

时间:2015-01-05 14:27:54

标签: ios xcode core-data swift share

当我尝试访问填充了CoreData数据的数组时。我收到了EXC_BAD_ACCESS错误。

这是我的代码:

var endPointList: Array<SettingsModel> = []

override func viewDidLoad() {

    var context = getManagedObjectContext()

    let fetchRequest = NSFetchRequest(entityName: "SettingsEndpoint")
    endPointList = context.executeFetchRequest(fetchRequest, error: nil) as [SettingsModel]

}

当我按下一个触发以下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 );
}

调试器指向以下行:

var endPointNameFromData:String = endPoint.name as String

奇怪的是,如果我在viewDidLoad()方法中执行此代码,它就会运行。这是为什么?

更新:

现在有一些来自Mundi的编辑。我得到一个稍微不同的错误:

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'

我的SettingsModel类:

import UIKit
import CoreData

@objc(SettingsModel)
class SettingsModel: NSManagedObject {

    @NSManaged var name:String
    @NSManaged var webservice:String
    @NSManaged var service:String

}  

1 个答案:

答案 0 :(得分:0)

从Core Data获取时,通常需要将结果转换为正确的类型。仅仅声明某种类型的变量是不够的。

最好不要使用AnyObject,而应使用正确的NSManagedObject子类。

endPointList = context.executeFetchRequest(fetchRequest, error: nil) as [EndPoint]
for endPoint : EndPoint in endPointList {
   println(endpoint.name)
}