2017-10-04 147 views
1

我正在使用以下代碼來安排段中的聯繫人數組(例如,在「A」部分下應顯示前綴「A」的聯繫方式)。如果有4-5個接觸點,則需要20秒來處理。循環處理時間過長

你可以請檢查這裏有什麼問題嗎?或任何其他替代品。

let finalArr = NSMutableArray() 

    for contactDetail in conatctsArr { 

     let name = (contactDetail as! Dictionary)["givenName"] ?? ""// Getting First character of name 
     var key = String() 
     if name.characters.count > 0 { 
      let index1 = name.index((name.startIndex), offsetBy: 1) 
      key = name.substring(to: index1) 
     } 
     else { 
      key = "" 
     } 

     // getting all contatcts starting with particular character 
     let predicate=NSPredicate(format: "SELF.givenName beginswith[c] %@",key) 

     let filteredArr = (conatctsArr as NSArray).filtered(using: predicate) 

     var dic = Dictionary<String, Any>() 
     dic["key"] = key 
     dic["values"] = filteredArr 

     if filteredArr.count > 0 && !(finalArr.contains(dic)) { 
      finalArr.add(dic) 
     } 
    } 

回答

1

在每個循環中處理後從陣列中刪除過濾的元素可能會提高性能。嘗試:

let finalArr = NSMutableArray() 
    var processingArray = NSMutableArray(array:conatctsArr) 

    while processingArray.count > 0 { 
     let contactDetail = processingArray[0] 
     let name = (contactDetail as! Dictionary)["givenName"] ?? "" 
     var key = String() 
     if name.characters.count > 0 { 
      let index1 = name.index((name.startIndex), offsetBy: 1) 
      key = name.substring(to: index1) 
     } 
     else { 
      key = "" 
     } 

     let predicate=NSPredicate(format: "SELF.givenName beginswith[c] %@",key) 
     let filteredArr = processingArray.filtered(using: predicate) 

     if filteredArr.count > 0 { 
      var dic = Dictionary<String, Any>() 
      dic["key"] = key 
      dic["values"] = filteredArr 
      finalArr.add(dic) 
     } 

     processingArray.removeObjects(in: filteredArr) 
    } 
1

在您的代碼中,對同一個密鑰進行多次過濾。試試:

let finalArr = NSMutableArray() 
    for contactDetail in conatctsArr 
{ 
    let keysArray = [「A」, 「B」, 「C」,…. 「Z」] 
    for key in keysArray 
    { 
     let predicate=NSPredicate(format: "SELF.givenName beginswith[c] %@",key) 
     let filteredArr = (conatctsArr as NSArray).filtered(using: predicate) 
     var dic = Dictionary<String, Any>() 
     dic["key"] = key 
     dic["values"] = filteredArr 
     if filteredArr.count > 0) { 
      finalArr.add(dic) 
      } 
    } 
}