我想弄清楚为什么我的数组会动态更新?
我有以下课程
class LocationData {
var address: String = ""
var city: String = ""
var deviceName: String = ""
var deviceId: String = ""
var state: String = ""
}
然后我有以下功能
func fetchLocationItems(sortByKey1: String, sortByKey2: String, deviceID: String, isAsecending: Bool) -> [LocationData]{
var locationObjectArray = [LocationData]()
var locationData = LocationData()
let context: NSManagedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
do {
let request = NSFetchRequest(entityName: "Location")
let sortDescriptor1 = NSSortDescriptor(key: sortByKey1, ascending: isAsecending)
let sortDescriptor2 = NSSortDescriptor(key: sortByKey2, ascending: isAsecending)
request.sortDescriptors = [sortDescriptor1, sortDescriptor2]
let results = try locationContext.executeFetchRequest(request)
var count = 0
if results.count > 0 {
for item in results as! [NSManagedObject] {
if item.valueForKey("deviceID") as! String == deviceID {
locationData.deviceId = item.valueForKey("deviceID") as! String
locationData.address = item.valueForKey("address") as! String
locationData.city = item.valueForKey("city") as! String
locationData.state = item.valueForKey("state") as! String
locationData.deviceName = item.valueForKey("deviceName") as! String
locationObjectArray.insert(locationData, atIndex: count)
count++
}
}
//try context.save()
}
} catch {
print("There was error getting data")
}
return locationObjectArray
}
所以我在coredata有4条记录。第一次通过" for item loop",将locationDate插入到locationObjectArry
第二次循环时,位于索引0的locationObjectArray中的值将使用新值进行更新,例如
locationData.deviceId = item.valueForKey("deviceID") as! String
locationData.address = item.valueForKey("address") as! String
等等。
所以在循环结束时,locationObjectArray [0..4]的值都与最后一条记录的值相同。
知道可能是什么问题吗?
答案 0 :(得分:1)
因为你的对象在每个循环中都不是init新的。所以对象仍然是相同的
尝试:
for item in results as! [NSManagedObject] {
if item.valueForKey("deviceID") as! String == deviceID {
// init new LocationData
var locationData = LocationData()
locationData.deviceId = item.valueForKey("deviceID") as! String
locationData.address = item.valueForKey("address") as! String
locationData.city = item.valueForKey("city") as! String
locationData.state = item.valueForKey("state") as! String
locationData.deviceName = item.valueForKey("deviceName") as! String
locationObjectArray.insert(locationData, atIndex: count)
count++
}
}