BAD_EXC_ACCESS检查数据是否存在:SWIFT

时间:2014-10-02 12:29:34

标签: swift ios8 exc-bad-access managedobjectcontext

我有UITableViewController我有数据。如果您点按该行,则可以修改现有数据,如果点击UIBarButtonItem中的+,则会添加新信息。当我的Segue通过核心数据对象(vc.managedObjectID)我的"详细信息"视图控制器检查firstName字段是否有数据或没有数据。

Objective-C 中,我会做这样的事情

- (void)refreshInterface
{
    CoreDataHelper *cdh = [CoreDataHelper sharedHelper];
    Cues *existingCues = (Cues*)[cdh.context existingObjectWithID:_cuesNSManagedObjectID error:nil];

    if (!existingCues.cuesName)
    {
        _cueNameTextField.text           = nil;
        self.cueDescriptionTextView.text = nil;
    }
    else
    {
        _cueNameTextField.text           = existingCues.cuesName;
        self.cueDescriptionTextView.text = existingCues.cuesDescription;
    }
}

我在查看firstName中是否有任何数据时遇到问题:var firstName = playerInformation.firstName仅在添加新对象(意味着playerInformatin为空)时导致EXC_BAD_ACCESS,当我点击查看现有数据时数据返回正确的数据。如何在Swift中检查playerInfomation是空的(新记录)还是有数据(现有数据)?

func refreshInterface(){

    if managedObjectID != nil {
        var playerInformation = managedObjectContext?.existingObjectWithID(managedObjectID!, error: nil) as? PlayerInformation

        var firstName = playerInformation!.firstName //EXC_BAD_ACCESS
        println("firstName \(firstName)")
    }
}

prepareForSegue

   override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        if segue.identifier == "addPlayerInformationDetail" {

            println("addPlayerInformationDetail")

            let context = self.fetchedResultsController.managedObjectContext

            let entity  = self.fetchedResultsController.fetchRequest.entity

            let playerInformation = NSEntityDescription.insertNewObjectForEntityForName(entity.name, inManagedObjectContext: managedObjectContext!) as PlayerInformation?

            var vc  = segue.destinationViewController as PlayerInformationDetailTableViewController

            vc.managedObjectID = playerInformation?.objectID

        } else if segue.identifier == "editPlayerInformationDetail" {


            println("editPlayerInformationDetail")

            var indexPath:NSIndexPath = tableView.indexPathForSelectedRow()!

            var vc                    = segue.destinationViewController as PlayerInformationDetailTableViewController

            vc.managedObjectID        = self.fetchedResultsController.objectAtIndexPath(indexPath).objectID

        }

2 个答案:

答案 0 :(得分:0)

您可以像这样使用条件let

if let firstName = playerInformation?.firstName {
    println("firstName \(firstName)")
}

这只会解除可选值,如果它不是nil,则可以避免崩溃。

答案 1 :(得分:0)

出于某种原因,这有效:

var playerInformation = managedObjectContext?.existingObjectWithID(managedObjectID!, error: nil)
var firstName: AnyObject? = playerInformation?.valueForKey("firstName")
println("firstName \(firstName)")

如果我将managedObjectContext子类化为PlayerInformation,我会得到EXC_BAD_ACCESS