我正在使用Xcode 7.1.0在Swift中为IOS制作应用程序
我在一个功能中有一个开关盒。 当我放置断点时,我注意到在一个案例中,每次执行大小写时都会执行两行代码。它似乎只是一行,其余的只执行一次(就像它应该的那样)。
jsonobject的行只执行一次。 具有saveCurrentMeasurementDetailsToCoreData函数的行将执行两次。
这怎么可能?
这是我的代码:
private func apiReceivedDetailData(state: ApiCall.ApiState, data : AnyObject){
switch state{
case ApiCall.ApiState.Successful:
// Put the values in the researchmodel and update the table with this global measurement information
let jsonObject : NSObject = data as! NSObject
//save all data of current measurement to CoreData
MeasurementRepository.Instance.saveCurrentMeasurementDetailsToCoreData()
case ApiCall.ApiState.InvalidCredentials:
showFailure(data as! String)
case ApiCall.ApiState.NoConnection:
showFailure(data as! String)
default:
showFailure("Onbekende fout opgetreden")
}
}
首先调用api:
func getMesDetailData() {
let apiCall = ApiCall()
apiCall.createCall(ApiCall.ApiCall.Meting, id: _researchModel.Id)
apiCall.dataAvailable = apiReceivedDetailData
}
func createCall(apiCall : ApiCall, id : Int){
createCall(apiCall, id : id, postString : nil)
}
func createCall(apiCall : ApiCall, id : Int?, postString : String?){
var url : NSURL
if id == nil{
url = NSURL(string: _apiUrl + connectToApi(apiCall))!
}
else{
url = NSURL(string: _apiUrl + connectToApi(apiCall) + String(id!))!
}
let request = NSMutableURLRequest(URL: url)
if postString != nil {
let postData : NSData = (postString! as NSString).dataUsingEncoding(NSUTF8StringEncoding)!
// create the request
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type")
request.HTTPBody = postData
}
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
}
private func connectToApi(apiCall : ApiCall) -> String{
switch apiCall {
case .Meting:
return "/meting/"
case .LastMeting:
return "/meting/last"
case .Login:
return "/login/"
case .Training:
return "/training/"
case .Sport:
return "/sport/"
case .Type:
return "/type/"
case .Goal:
return "/goal/"
default:
return ""
}
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
switch (_responseCode){
case 200, 201, 400:
// Succesfull
var jsonResult: AnyObject? = try? NSJSONSerialization.JSONObjectWithData(_data, options: NSJSONReadingOptions.MutableContainers)
if jsonResult == nil {
jsonResult = ""
}
dataAvailable!(
state: _responseCode != 400 ? ApiState.Successful : ApiState.BadRequest,
data: jsonResult!
)
case 403:
// Faulty credentials
dataAvailable!(state: ApiState.InvalidCredentials, data: _faultCredentialsMessage)
case 429:
// Too many requests
dataAvailable!(state: ApiState.TooManyRequests, data: _tooManyRequestsMessage)
default:
// Unknow status code
let responseMessage = _unknowStatusCode + " Status code: " + String(_responseCode)
dataAvailable!(state: ApiState.UnknowStatusCode, data: responseMessage)
}
}