[英]detachNewThreadSelector crashes the app randomly
我正在開發一個iphone應用程序,我在其中提取RSS提要然后解析它們。我的代碼如下:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSLog(@"in view did appear");
if ([stories count] == 0) {
NSString * path = @"http://www.shire.com/shireplc/rss.jsp";
//[self parseXMLFileAtURL:path];
//[self performSelectorInBackground:@selector(parseXMLFileAtURL:) withObject:path];
NSLog(@"internet is %d",[self checkInternet]);
if([self checkInternet]==1)
[NSThread detachNewThreadSelector:@selector(parseXMLFileAtURL:)
toTarget:self withObject:path];
}
}
- (void)parseXMLFileAtURL:(NSString *)URL
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
stories = [[NSMutableArray alloc] init];
//you must then convert the path to a proper NSURL or it won't work
NSURL *xmlURL = [NSURL URLWithString:URL];
// here, for some reason you have to use NSClassFromString when trying to alloc NSXMLParser, otherwise you will get an object not found error
// this may be necessary only for the toolchain
rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
// Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
[rssParser setDelegate:self];
// Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
[rssParser setShouldProcessNamespaces:NO];
[rssParser setShouldReportNamespacePrefixes:NO];
[rssParser setShouldResolveExternalEntities:NO];
[rssParser parse];
[pool release];
}
誰能告訴我哪里出錯了? 我的日志如下:log:[切換到線程12803] [切換到線程12035] 2011-05-10 11:31:30。9。9年度報告[454:490b]找到文件並開始解析[切換到線程14339] 2011- 05-10 11:32:04。73年度報告[454:640b]找到文件並開始解析[切換到線程13827] [切換到線程13827]程序接收信號:“EXC_BAD_ACCESS”。
gdb stack trace at 'putpkt: write failed':
0 gdb-arm-apple-darwin 0x0019026b remote_backtrace_self + 54
//您可以使用該方法,如果您不必更新UserInterface,則更安全
[self performSelectorInBackground:@selector(parseXMLFileAtURL:) withObject:path];
如果UserInterface也需要更新,你可以先在后台解析數據,然后用方法更新ui。
[self performSelectorOnMainThread:@selector(myUpdateUI) withObject:nil waitUntilDone:YES];
我不確定,但我猜這個方法的參數在某些時候被釋放。 您能否確保該方法parseXMLFileAtURL
存在該URL
最后,我使用一個標志來檢查視圖是否出現(通過在viewdidAppear中使標志為true)並且如果視圖沒有出現,則不要運行線程函數。這解決了問題!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.