2012-07-10 51 views
0

當我的應用程序崩潰時,nsstring獲取URL的內容。我的應用程序崩潰時,試圖獲取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];IBAction。我做錯了什麼?

(Xcode的4.3的Mac OS X Lion中,iPhone模擬器5.1)

回答

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!"]; 
} 
+0

但 - 如何把它在後臺運行? – theShay 2012-07-10 16:14:18

+0

您仍然可以使用'performSelectorInBackground'在後臺運行您的網頁代碼。當在後臺運行的選擇器完成時,從後臺線程調用'performSelectorOnMainThread'來更新UI。 checkLogin中的 – mopsled 2012-07-10 16:17:22

+0

做了'[self webStuffDone];'最後? – theShay 2012-07-10 17:03:40

0

嘗試使用

 - (id)performSelector:(SEL)aSelector withObject:(id)anObject. 
+0

但是 - 如何在後臺運行它? – theShay 2012-07-10 16:14:44

+0

我覺得最好的是使用GCD,或者你也可以使用另一個線程。 – khushalbokadey 2012-07-10 16:16:35

+0

dispatch_queue_t getdata = dispatch_queue_create(「any string」,NULL); dispatch_async(getdata,^ { //代碼 }); – khushalbokadey 2012-07-10 16:22:51

相關問題