NSTimer를 사용하여 x 초마다 함수를 실행할 때이 오류 메시지가 나타나는 이유는 무엇입니까?

가로 질러 가다

여기에 제안 된대로 x 초마다 함수를 실행하기 위해 NSTime을 사용하고 있습니다 .

내 문제는 x 시간이 지나고 함수를 실행할 때가되면이 오류 메시지가 표시된다는 것입니다.

2015-04-06 11:55:51.898 myapp[21611:1186926] -[myapp.ViewController getJson(sharedData.jsonUrl)]: unrecognized selector sent to instance 0x7fff48761d60
2015-04-06 11:55:51.902 myapp[21611:1186926] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[myapp.ViewController getJson(sharedData.jsonUrl)]: unrecognized selector sent to instance 0x7fff48761d60'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000101497a75 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x0000000102fefbb7 objc_exception_throw + 45
    2   CoreFoundation                      0x000000010149ed1d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
    3   CoreFoundation                      0x00000001013f69dc ___forwarding___ + 988
    4   CoreFoundation                      0x00000001013f6578 _CF_forwarding_prep_0 + 120
    5   Foundation                          0x00000001018cf844 __NSFireTimer + 83
    6   CoreFoundation                      0x00000001013ff6c4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20
    7   CoreFoundation                      0x00000001013ff285 __CFRunLoopDoTimer + 1045
    8   CoreFoundation                      0x00000001013c259d __CFRunLoopRun + 1901
    9   CoreFoundation                      0x00000001013c1bc6 CFRunLoopRunSpecific + 470
    10  GraphicsServices                    0x00000001055a0a58 GSEventRunModal + 161
    11  UIKit                               0x0000000101d2a580 UIApplicationMain + 1282
    12  maybe                               0x0000000100ed55ee top_level_code + 78
    13  myapp                               0x0000000100ed562a main + 42
    14  libdyld.dylib                       0x00000001037cb145 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

이 기능이 자체적으로 테스트 한대로 작동한다는 것을 알고 있습니다.

NSTimer로 함수를 호출하는 데 사용하는 코드는 다음과 같습니다.

override func viewDidLoad() {
    super.viewDidLoad()
    var timer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "getJson(sharedData.jsonUrl)", userInfo: nil, repeats: true)
}

이 오류가 발생하는 이유를 잘 모르겠습니다. 나는 이것을 배웠던 SO에 대한 질문의 코드와 정확히 동일하도록 호출 및 함수 자체에서 인수를 제거하려고 시도했지만 운이 없었습니다.

나는 이것을 신속하게 쓰고있다.

여기에 조금 더 많은 정보가 있습니다. getJsonJSON 파일을 다운로드하고 일부 값을 배열에 추가하는 함수입니다. sharedData싱글 톤 클래스-다른 뷰 컨트롤러에서 사용하는 데 필요한 값을 저장하는 데 사용하고 있습니다. jsonUrl해당 클래스의 변수 중 하나입니다. 그래서 sharedData.jsonUrl그 변수를 클래스에서 꺼내는 것입니다. \

편집하다:

다음은 지금 사용하려는 코드입니다. var timer = NSTimer.scheduledTimerWithTimeInterval (0.2, target : self, selector : "getJson :", userInfo : nil, repeats : true)

정확한 오류 메시지는 다음과 같습니다.

2015-04-06 16:16:56.160 myapp[22712:1284267] -[myapp.settingsViewController getJson:]: unrecognized selector sent to instance 0x7f8c88c7d810
2015-04-06 16:16:56.165 myapp[22712:1284267] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[myapp.settingsViewController getJson:]: unrecognized selector sent to instance 0x7f8c88c7d810'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010a491a75 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x000000010bfe9bb7 objc_exception_throw + 45
    2   CoreFoundation                      0x000000010a498d1d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
    3   CoreFoundation                      0x000000010a3f09dc ___forwarding___ + 988
    4   CoreFoundation                      0x000000010a3f0578 _CF_forwarding_prep_0 + 120
    5   Foundation                          0x000000010a8c9844 __NSFireTimer + 83
    6   CoreFoundation                      0x000000010a3f96c4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20
    7   CoreFoundation                      0x000000010a3f9285 __CFRunLoopDoTimer + 1045
    8   CoreFoundation                      0x000000010a3bc59d __CFRunLoopRun + 1901
    9   CoreFoundation                      0x000000010a3bbbc6 CFRunLoopRunSpecific + 470
    10  GraphicsServices                    0x000000010e59aa58 GSEventRunModal + 161
    11  UIKit                               0x000000010ad24580 UIApplicationMain + 1282
    12  myapp                               0x0000000109ed41ce top_level_code + 78
    13  myapp                               0x0000000109ed420a main + 42
    14  libdyld.dylib                       0x000000010c7c5145 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

get getJson함수는 다음과 같습니다.

func getJson() {
    let urlPath = sharedData.jsonUrl.absoluteString
    let url: NSURL = NSURL(string: urlPath!)!
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in

        if error != nil {
            // If there is an error in the web request, print it to the console
            println(error.localizedDescription)
        }

        var err: NSError?


        var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary

        if err != nil {
            // If there is an error parsing JSON, print it to the console
            println("JSON Error \(err!.localizedDescription)")
        }

        let json = JSON(jsonResult)

        var teamCount = json["teamCount"].string! // Number in array
        var teamCountInt: Int = teamCount.toInt()! // Converts to integer

        for index in 0...teamCountInt - 1 { // loop for number in array
            let teamJson = json["teams"][index]["\(index)"].string! //
            sharedData.teamsArray.append(teamJson) // Appends to array in shared data
        }
        println(sharedData.teamsArray) // For debug - delete after
    })
    task.resume()
}

이 함수는 Swifty-json을 사용합니다 .

압둘라

getJson () 메소드를 다음과 같이 변경하십시오.

class SomeGoodClassName {
    func getJson(timer: NSTimer) {
        //Directly use shareData.jsonUrl here to get json data

        //... more code
    }
}

NSTimer 초기화

let jsonLoader = SomeGoodClassName()

override func viewDidLoad() {
    super.viewDidLoad()
    var timer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: jsonLoader, selector: "getJson", userInfo: nil, repeats: true)
}

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관