ฉันมีปัญหาในการดึงข้อมูลหลัก (รหัสที่แสดงด้านล่าง) ฉันสร้างโปรเจ็กต์ XCode ใหม่และดาต้าโมเดลด้วยแอตทริบิวต์สามรายการ username
, password
และ testnumbers
การใช้โค้ดด้านล่างฉันเก็บค่าไว้ในนั้นและส่งออกผลลัพธ์ไปยังบันทึก (ด้านล่างขวาคือเอาต์พุตนั้นจากบรรทัดของโค้ด println(results)
ที่ใส่ความคิดเห็นไว้) เห็นได้ชัดว่ามันเก็บทุกอย่างถูกต้องฉันคิดว่า
ตอนนี้ฉันแสดงความคิดเห็นส่วนนั้นแล้วและตอนนี้ต้องการดึงค่าที่เก็บไว้ภายใต้ username
, password
และ testnumbers
การพิมพ์ result.password
ดูเหมือนจะใช้ได้ดีกับโค้ด แต่ในโค้ดขณะพยายามพิมพ์ result.testnumbers
และ result.username
มันบอกว่า "'AnyObject' ไม่มีสมาชิกชื่อ 'testnumbers/username'" ฉันไม่แน่ใจว่าเกิดอะไรขึ้น เนื่องจากผลลัพธ์ก่อนหน้าของฉันแสดงการจัดเก็บสิ่งเหล่านี้อย่างถูกต้อง
ฉันได้ลองทำโปรเจ็กต์ง่ายๆ นี้ซ้ำสองสามครั้ง โดยสร้าง datamodel ก่อนเสมอ และตรวจดูให้แน่ใจว่าสะกดทุกอย่างถูกต้อง ฯลฯ สิ่งเดียวกันนี้ยังคงเกิดขึ้น
นี่คือรหัส:
import UIKit
import CoreData
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
var context:NSManagedObjectContext = appDel.managedObjectContext!
var newUser = NSEntityDescription.insertNewObjectForEntityForName("Users",
inManagedObjectContext: context) as NSManagedObject
newUser.setValue("Mark", forKey: "username")
newUser.setValue("pass", forKey: "password")
newUser.setValue("12345", forKey: "testnumbers")
context.save(nil)
var request = NSFetchRequest(entityName: "Users")
request.returnsObjectsAsFaults = false
var results = context.executeFetchRequest(request, error: nil)
if results?.count > 0 {
for result: AnyObject in results! {
//println(results) // this printed everything fine
println(result.password)
println(result.testnumbers)
println(result.username)
}
}
}
}
นี่คือผลลัพธ์ของสิ่งที่ println(results)
แรกให้ฉัน:
ทางเลือก ([ (เอนทิตี: ผู้ใช้; id: 0xd000000000040000 ; ข้อมูล: { รหัสผ่าน = ผ่าน; testnumbers = 12345; ชื่อผู้ใช้ = เครื่องหมาย; }), (เอนทิตี: ผู้ใช้; id: 0xd000000000080000 ; ข้อมูล: { รหัสผ่าน = ผ่าน; testnumbers = 12345; ชื่อผู้ใช้ = Mark; }), (เอนทิตี: ผู้ใช้; id: 0xd0000000000c0000 ; ข้อมูล: { รหัสผ่าน = ผ่าน; testnumbers = 12345; ชื่อผู้ใช้ = ทำเครื่องหมาย; })])
ภาพหน้าจอ XCode จริง: