我有一个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
}