为什么NSOperation在完成上一次操作之前就开始了?

时间:2016-03-28 20:11:07

标签: ios swift concurrency nsoperation nsoperationqueue

我正在尝试下一个:

  1. 我收到了Alamofire的回复,填了一个数组
  2. 打印此阵列
  3. 为此我做了:

    var queue = NSOperationQueue()
    
    let firstOperation = NSBlockOperation(block: {
        let getMyProfileURL = "\(self.property.host)\(self.property.getMyProfile)"
         Alamofire.request(.POST, getMyProfileURL, parameters: self.userParameters.profileParameteres, encoding: .JSON).responseJSON { response in
             do {
                  let json = JSON(data: response.data!)
                  print(json)
    
                  if json["user"].count > 0 {
                      self.profileDetails.append(ProfileDetailsModel(json: json["user"]))
                  }
              }
          }
    })
    
    firstOperation.completionBlock = {
         print("firstOperation completed")
    }
    
    queue.addOperation(firstOperation)
    
    let secondOperation = NSBlockOperation(block: {
         print(self.profileDetails)
    })
    
    secondOperation.addDependency(firstOperation.completionBlock)
    
    secondOperation.completionBlock = {
        print(self.profileDetails)
    }
    
    queue.addOperation(secondOperation)
    

    所以,在理论上,首先它需要填充我的数组,完成这个任务(块),然后再打印那些数组。但我明白了:

    firstOperation completed
    [] -> self.profileDetails from the secondOperation
    [] -> self.profileDetails from the secondOperation completion block
    and just here I get my JSON from the Alamofire 'do' block
    

    那么,我做错了什么?我怎么能解决它会按照我想要的方式工作呢?

2 个答案:

答案 0 :(得分:0)

在第一个操作完成之后(例如,在第一个操作块结束时),不要添加第二个操作。

答案 1 :(得分:0)

首先,您必须了解Alamofire请求始终在单独的线程中执行。

所以你的firstOperation没用。你不需要它,因为Alamofire已经是异步的。

var queue = NSOperationQueue()

let secondOperation = NSBlockOperation(block: {
    print(self.profileDetails)
})


secondOperation.completionBlock = {
    print(self.profileDetails)
}

let getMyProfileURL = "\(self.property.host)\(self.property.getMyProfile)"
Alamofire.request(.POST, getMyProfileURL, parameters: self.userParameters.profileParameteres, encoding: .JSON).responseJSON { response in
    do {
        let json = JSON(data: response.data!)
        print(json)

        if json["user"].count > 0 {
            self.profileDetails.append(ProfileDetailsModel(json: json["user"]))
        }
    }

    print("Alamofire.request completed") // instead of: print("firstOperation completed")

    queue.addOperation(secondOperation)
}