循环过程需要很长时间才能完成

时间:2017-10-04 07:36:29

标签: ios swift xcode performance memory

我正在使用以下代码来安排部分中的联系人数组(例如,使用前缀&#34联系; 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)
        }
    }

2 个答案:

答案 0 :(得分: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 :(得分: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)
            }
    }
}