Swift - 致命错误:无法解包Optional.None

时间:2014-06-19 16:01:00

标签: uitableview core-data swift ios8

我正在尝试获取Core数据对象并在UITableView中显示它们。

我有DBEmployess个对象,当我尝试获取其name属性时出现错误

fatal error: Can't unwrap Optional.None

这是我的代码

DBEmployess.h

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@class DBProjects;

@interface DBEmployess : NSManagedObject

@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * designation;
@property (nonatomic, retain) NSNumber * age;
@property (nonatomic, retain) DBProjects *projects;

@end

DBEmployess.m

#import "DBEmployess.h"
#import "DBProjects.h"


@implementation DBEmployess

@dynamic name;
@dynamic designation;
@dynamic age;
@dynamic projects;

@end

MyProject的桥接-Header.h

#import "MBProgressHUD.h"
#import "DBEmployess.h"

UITableView方法

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell : UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell
    if(cell == nil) {
        cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
    }

    let employee : DBEmployess? = self.employessArray.objectAtIndex(indexPath.row) as? DBEmployess

    if(employee != nil) {
        cell!.textLabel.text = employee!.valueForKey("name").description
    }

    return cell!
}

如果我打印employee对象,我会

(DBEmployess?) employee = Some {
  Some = 0x0000000111702670 {
    CoreData.NSManagedObject = {
      ObjectiveC.NSObject = {}
    }
  }

知道我做错了吗?

更新

我发现实际问题是在保存Core数据时。如果我在NSManagedObject属性中设置硬编码字符串,则可以完全访问它并显示在UITableView中。但是,如果我设置UITextField文字的值,它会成功保存,但无法解开。

这是我的核心数据方法

func addNewEmployee() {
    let delegate = UIApplication.sharedApplication().delegate as AppDelegate
    let context = delegate.managedObjectContext
    let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName("DBEmployess", inManagedObjectContext: context) as NSManagedObject
    newManagedObject.setValue(self.txtName.text, forKey: "name")
    newManagedObject.setValue(self.txtDesignation.text, forKey: "designation")
    newManagedObject.setValue(self.txtAge.text, forKey: "age")

    // Save the context.
    var error: NSError? = nil
    if !context.save(&error) {
        var alert = UIAlertController(title: "Error", message: "Could not save employee \(error!.localizedDescription)", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)

    } else {
        var alert = UIAlertController(title: "Saved", message: "Employee saved successfully", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)
    }
}

0 个答案:

没有答案