我正在尝试从Core Data中获取一些数据并遇到了一些小问题。我可以毫无问题地获取数据。当我尝试获取特定数据(即data.fooBar
)时,它会引发错误:
“'AnyObject'没有成员名称'fooBar'
如果我println(data)
,则会显示fooBar
确实存在数据。
我不确定为什么会这样做。我试图寻找答案并尝试了许多不同的东西,但似乎都没有。任何帮助都会很棒。谢谢。 :)
var results : Array<AnyObject> = []
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
//get the data for that storedItem
var appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
var context:NSManagedObjectContext = appDel.managedObjectContext!
let req = NSFetchRequest(entityName: "storedItems")
let name:String = results[indexPath.row].name
req.predicate = NSPredicate(format: "name == %@", name)
req.returnsObjectsAsFaults = false
var tapResults = context.executeFetchRequest(req, error: nil)!
for item in tapResults {
println(item) //works, shows all data correctly(including subText)
println(item.name) //works, the only one that does for some reason???
println(item.subText) //Error 'AnyObject' does not have a member name 'subText'
}
以下是println(item)
println(item) <NSManagedObject: 0x7f04be60> (entity: storedItems; id: 0x7f041de0 <x-coredata://DD4F8E68-2234-46B5-B1D8-AE2F75245C63/storedItems/p1> ; data: {
alarmSound = default;
isDefault = 0;
name = "test";
sliderHours = 0;
sliderMinutes = 0;
sliderSeconds = 0;
subText = "00:00:00";
更新:根据对vacawama回答的讨论(谢谢Aaron)。如需正确解决方案,请参阅我接受的答案。
我的itemObj类
@objc(itemObj)
class itemObj: NSManagedObject {
@NSManaged var name:String!
@NSManaged var sliderHours:NSNumber
@NSManaged var sliderMinutes:NSNumber
@NSManaged var sliderSeconds:NSNumber
@NSManaged var subText:String!
@NSManaged var alarmSound:String!
@NSManaged var isDefault:NSNumber
}
我的AddItem VC:
var tResults = (context.executeFetchRequest(req, error: nil))
for item in tResults as [itemObj!] {
println(item.name)
println(item.subText)
}
答案 0 :(得分:3)
executeFetchRequest
返回AnyObject
的可选数组。你不应该强行打开它(这会导致崩溃)。因此,可选择解包并执行可选的强制转换(as?
)以确保类型正确:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
let req = NSFetchRequest(entityName: "storedItems")
let name:String = results[indexPath.row].name
req.predicate = NSPredicate(format: "name == %@", name)
req.returnsObjectsAsFaults = false
let tapResults = context.executeFetchRequest(req, error: nil)
if let presentResults = tapResults {
if let castedResults = presentResults as? [MyManagedObjectSubclass] {
for item in castedResults {
println(item)
println(item.name)
println(item.subText)
}
}
}
}
我还将所有var
更改为let
,因为它们不需要变异。
只需将MyManagedObjectSubclass
替换为NSManagedObject
子类。