0

我有一个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 仅在添加新对象时导致 EXC_BAD_ACCESS(意味着 playerInformatin 为空),当我点击查看现有数据时,它返回正确数据。如何在 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

        }
4

2 回答 2

0

您可以使用let这样的条件:

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

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

于 2014-10-02T12:42:28.880 回答
0

出于某种原因,这有效:

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

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

于 2014-10-03T00:12:33.523 回答