0

nsstringがURLのコンテンツを取得すると、アプリがクラッシュしました。

website = [NSString stringWithFormat:@"hidden."]; 
contents = [NSString stringWithContentsOfURL:[NSURL URLWithString:website] encoding:NSUTF8StringEncoding error:nil];

クラッシュログは次のとおりです。

void _WebThreadLockFromAnyThread(bool), 0x865cc40: Obtaining the web lock from a thread other than the main thread or the web thread. UIKit should not be called from a secondary thread.
2012-07-10 11:15:17.654 MyApplication[1505:19407] OK // some output
2012-07-10 11:15:17.660 MyApplication[1505:19407] bool _WebTryThreadLock(bool), 0x865cc40: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now...
1   WebThreadLock
2   -[UITextRangeImpl isEmpty]
3   -[UITextRange(UITextSelectionAdditions) _isCaret]
4   -[UITextSelectionView setCaretBlinks:]
5   -[UIKeyboardImpl setCaretBlinks:]
6   -[UIKeyboardImpl setDelegate:force:]
7   -[UIKeyboardImpl setDelegate:]
8   -[UIPeripheralHost(UIKitInternal) _reloadInputViewsForResponder:]
9   -[UIResponder(UIResponderInputViewAdditions) reloadInputViews]
10  -[UIResponder(Internal) _windowBecameKey]
11  -[UITextField _windowBecameKey]
12  -[UIWindow makeKeyWindow]
13  -[UIWindow makeKeyAndVisible]
14  -[MyApplicationAppDelegate checkLogin]
15  -[NSThread main]
16  __NSThread__main__
17  _pthread_start
18  thread_start

コードは[self performSelectorInBackground:@selector(checkLogin) withObject:nil];fromで呼び出されIBActionます。私が間違っていることは何ですか?

(Xcode 4.3、Mac OS X Lion、iPhone Simulator 5.1)

4

2 に答える 2

3

そのエラーメッセージによると、バックグラウンドスレッドからオブジェクトを更新しようとしてUIKitおり、UIはメインスレッドからのみ更新できます。

代わりに、を使用self performSelectorOnMainThreadしてメインスレッドにコールバックし、Web呼び出しが戻ったときに受け取った情報でUIを更新します。

メインスレッドから:

[self performSelectorInBackground:@selector(checkLogin) withObject:nil];

バックグラウンドで:

- (void)checkLogin {
    // Do web stuff
    ...

    [self performSelectorOnMainThread:@selector(updateUI) 
                           withObject:nil 
                        waitUntilDone:NO];
}

- (void)updateUI {
    [statusLabel setText:@"Done!"];
}
于 2012-07-10T15:37:12.530 に答える
0

使ってみて

      - (id)performSelector:(SEL)aSelector withObject:(id)anObject.
于 2012-07-10T15:43:25.290 に答える