我正在尝试获取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)
}
}