我正在运行两组相同的代码,但是,我不明白为什么第二组代码失败。如果我从中更改线
println(result.password)
至println(result.token)
我收到'AnyObject' does not have a member named 'token'
以下是工作代码:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var context: NSManagedObjectContext = appDel.managedObjectContext!
var newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as! NSManagedObject
newUser.setValue("test-1", forKey: "token")
context.save(nil)
var request = NSFetchRequest(entityName: "Users")
var results = context.executeFetchRequest(request, error: nil)
if results!.count > 0 {
for result: AnyObject in results! {
println(result.password)
}
} else {
println("No results")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
如果我将行更改为println(result)
,我会收到打印输出,显示有一个名为token
的属性。
<NSManagedObject: 0x7ffa2945c3a0> (entity: Users; id: 0xd000000000040000 <x-coredata://749CCE65-5C4A-45F2-839C-195A94AFCDB6/Users/p1> ; data: <fault>)
<NSManagedObject: 0x7ffa2945c400> (entity: Users; id: 0xd000000000080000 <x-coredata://749CCE65-5C4A-45F2-839C-195A94AFCDB6/Users/p2> ; data: <fault>)
<NSManagedObject: 0x7ffa2945c460> (entity: Users; id: 0xd0000000000c0000 <x-coredata://749CCE65-5C4A-45F2-839C-195A94AFCDB6/Users/p3> ; data: <fault>)
<NSManagedObject: 0x7ffa2964b360> (entity: Users; id: 0xd000000000100000 <x-coredata://749CCE65-5C4A-45F2-839C-195A94AFCDB6/Users/p4> ; data: {
password = nil;
token = "test-1";
username = nil;
})
答案 0 :(得分:0)
即使println(result.password)
有效,我也很惊讶
问题是result
的类型。在for-in-loop中,您明确告诉Swift将result
作为AnyObject
提供:
for result: AnyObject in results! {
println(result.password)
}
现在AnyObject
没有任何名为token
或password
的成员。因此,即使您要存储的对象可能属于具有属性的类型,也无法访问这些属性
因此,在能够访问这些属性之前,您必须向下转换为所需的类型
这可以通过省略: AnyObject
来实现,假设results
是所需类型的数组。