在完成for循环内的网络调用的信号,然后移动到for循环中的下一个项目?

时间:2015-10-05 23:58:03

标签: ios swift

我如何告诉for循环转到Swift中数组的下一个项目?

for (key, value) in commentIds {

    NetworkHelper.makeNetworkCall(key, completionHandler:{
       //Tell current thread the for-loop is being called, to move on to the next item in the for loop?
    }

}

我打算在dispatch_async线程中使用for循环,所以它不会阻塞主线程。我设计这个错误..?我应该有旗帜吗?

修改

主线程中的标志似乎有效。网络呼叫完成后,翻转标志。

1 个答案:

答案 0 :(得分:2)

我会假设如果makeNetworkCall方法采用completionHandler参数,它将以异步方式执行其工作。鉴于此,for循环将在makeNetworkCall中为key中的每个commentIds调用var commentIdKeys: Array<KeyType>()? var keyIndex: Int? func startRequests() { commentIdKeys = Array(commentIds.keys) keyIndex = 0 processNextKey() } func processNextKey() { guard let keys = commentIdKeys, let index = keyIndex else { print("processNextKey() invoked without values set") return } guard keyIndex < keys.count else { commentIdKeys = nil keyIndex = nil print("Finished processing keys") return } NetworkHelper.makeNetworkCall(key, completionHandler:{ // Do some work self.keyIndex = ++index self.processNextKey() } }

如果你想连续处理它们而不是在前一个完成之前不启动它们,你需要创建一个键数组并写下这样的代码:

public class Turtle
{
    public string Name { get; set; }
    public string Color { get; set; }
}

public class Filter
{
    public string Name { get; set ;}
    public string Value { get; set ;}
}   

public class Test
{
    private List<Turtle> Turtles { get; set;}

    public Test()
    {
        Turtles = new List<Turtle>();
        Turtles.Add(
        {
            new Turtle { Name = "Gilly", Color = "Brown" },
            new Turtle { Name = "Flow", Color = "Green" },
            new Turtle { Name = "Howard", Color = "Yellow" },
            new Turtle { Name = "Mara", Color = "Black" },
            new Turtle { Name = "Slimer", Color = "Green" },
            new Turtle { Name = "Tor", Color = "Brown" },
            new Turtle { Name = "Quartz", Color = "Yellow" },
            new Turtle { Name = "Gilly", Color = "Green" },
            new Turtle { Name = "Flow", Color = "Green" },
            new Turtle { Name = "Howard", Color = "Brown" }
        })
    }

    public IEnumerable<Turtle> FilterTurtles(string name, string color)
    {
        // This is the current code, but it's not extensible. If I add more properties
        // to the Turtle class, then I have to add more conditional statements.
        if (name != null)
        {
            return from t in Turtles
                   where t.Name == name
                   select t;
        }
        else if (color != null)
        {
            return from t in Turtles
                   where t.Color == color
                   select t;
        }
        else
        {
            return Turtles;
        }
    }

    public IEnumerable<Turtle> FilterTurtlesWithLinq(List<Filter> filters)
    {
        // I want to use dynamic linq here. For example, I want something like this:
        // "select all the turtles which match the filters"

        return null;
    }       
}