我正在尋找從函數中讀取coredata中的數據並在事後循環結果的最佳方法。'AnyObject'沒有名爲'contactName'的成員阻止我的循環
我已經嘗試了很多方法,但似乎掛起了試圖獲取每個對象內的特定數據片斷。
這是我的設置。
func readData()->NSArray{
let entityName:String = "Properties"
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext
// Specify what this will be working with
let request = NSFetchRequest(entityName: entityName)
// This will return instance of the object needed. Without which this would be
// a pain to work with. This bit saves a few steps.
request.returnsObjectsAsFaults = false;
// Get the data and put it into a variable
var results = context.executeFetchRequest(request, error: nil)
return results!
}
而且我在這裏把它..
var properties = Properties()
var getInfo = properties.readData()
println(getInfo)
for eachInfo:AnyObject in getInfo{
println(eachInfo)
}
這轉儲出這樣的事情...
<NSManagedObject: 0x7f87fa711d60> (entity: Properties; id: 0xd000000000040000 <x-coredata://F627AD12-3CEC-4117-8294-616ADEE068DC/Properties/p1> ; data: {
acreage = 0;
conditionId = 0;
contactBusinessName = nil;
contactEmail = nil;
contactName = Bob;
contactPhoneNumber = 456456456;
isFav = nil;
latitude = 0;
longitude = 0;
price = 0;
propertyCity = nil;
propertyId = nil;
propertyState = nil;
propertyStreetAddress = nil;
propertyType = 0;
propertyZip = nil;
squareFeet = 0;
year = 0;
})
這是偉大的。但當我去訪問下面的代碼內的數據......
for eachInfo:AnyObject in getInfo{
println(eachInfo.contactName)
}
我得到以下錯誤。
「‘AnyObject’沒有一個名爲成員‘聯繫人姓名’」
我相信有一些簡單的我失蹤,但我不能找到它。
任何協助,甚至更好的方式將不勝感激。
已回答。
首先,將名稱空間添加到核心數據對象。 http://i.stack.imgur.com/qNNLo.png
其次,強類型的函數的輸出,以便數據輸入到自定義對象。在這種情況下,它被稱爲「屬性」。
func readData()->Array<Properties>{
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext
// Specify what this will be working with
let request = NSFetchRequest(entityName: entityName)
// This will return instance of the object needed. Without which this would be
// a pain to work with. This bit saves a few steps.
request.returnsObjectsAsFaults = false;
// Get the data and put it into a variable
var results = context.executeFetchRequest(request, error: nil)
return results! as Array<Properties>
}
最後,調用函數並遍歷數據。
var properties = Properties()
var getInfo = properties.readData()
for eachInfo in getInfo{
println(eachInfo.contactName)
}
即使我這樣做,在接收端它仍然想要像「AnyObject」一樣對待它。 出現問題的原因這個.. VAR性能=屬性() VAR的getInfo = properties.readData() 爲eachInfo:在陣列的getInfo {的println (eachInfo.contactName) } 這導致EXC_BAD_INSTRUCTION錯誤。 VAR屬性=屬性() VAR的getInfo = properties.readData() 用於eachInfo中的getInfo { 的println(eachInfo.contactName) } –
2014-09-19 18:56:27
你的方法確實工作。我只需確保在設置Coredata對象時添加了名稱空間。我會發布答案。 – 2014-09-19 19:07:42