I have a method for fething data from a database, this method works fine for all versions of iOS 10 and above, but for iOS 9 the method hangs after calling fetch if I try to get more than 512 items, here's the code:
internal func getAll(_ dictId:Int) -> [Word]? {
let dictFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Words")
dictFetch.predicate = NSPredicate(format: "dictionary = %@", dictId)
dictFetch.fetchLimit = 513
do {
print("getAll before fetching")
let res = try self.moc_.fetch(dictFetch) as? [Word]
print("getAll after fetching")
return res
} catch {
print("error: \(error)")
}
return nil
}
If I set fetchLimit to 512 or less, then this code works fine and I get the log:
getAll before fetching
getAll after fetching
But if I set fetchLimit to 513 or more, then this code gives me this log:
getAll before fetching
without any errors, just hangs.
For testing, I only called this method (without any others in the project) in AppDelegate. The same result. I also tried to call it asynchronously. Same. Also I changed the input value of 'dictionary' and sorting to check that this is because of a certain element in the table. Same again, no more than 512 elements. Table "Word" contains more than 6000 items, and everything works fine in iOS 10 and above. It hangs without 'fetchLimit' also. Please give me any advice.
I found a solution to my problem. For devices with ios 9 and below, created a loop that fetch 500 items from the database, until get all the necessary data. Maybe someone will come in handy.
// CHECK VERSION OF IOS
let fetchLimit = NSString(string: UIDevice.current.systemVersion).doubleValue >= 10 ? -1 : 500
internal func getAll(_ dictId:Int) -> [Word]? {
return getAll(dict, nil, nil)
}
internal func getAll(_ dict:Dictionary,_ aRes:[Word]?,_ lastReg:NSDate?) -> [Word]? {
let dictFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Words")
if lastReg != nil {
dictFetch.predicate = NSPredicate(format: "dictionary = %@ AND registration > %@", dict, lastReg!)
} else {
dictFetch.predicate = NSPredicate(format: "dictionary = %@", dictId)
}
let sort = NSSortDescriptor(key: "registration", ascending: true)
dictFetch.sortDescriptors = [sort]
if fetchLimit > 0 {
dictFetch.fetchLimit = fetchLimit
}
do {
if let res = try self.moc_.fetch(dictFetch) as? [Word] {
var aRes_ = aRes != nil ? aRes! + res : res
if res.count == fetchLimit {
return self.getAll(dict, aRes_, aRes_[aRes_.count - 1].registration)
}
return aRes_
}
return aRes
} catch {
Titles.l(self, "getAll_, error: \(error)")
}
return nil
}