2013-03-18 71 views
-1

我是IOS新手我需要在我的程序中實現NSThread,但是當它調用它時會顯示SIGABRT錯誤。我當前的代碼下面給出NSThread顯示SIGABRT

XMLParser.m

-(void)loadXML 
{ 
    categories =[[NSMutableArray alloc]init]; 
    NSString *filepath =[[NSBundle mainBundle]pathForResource:@"cd_catalog" ofType:@"xml"]; 
    NSData *data =[NSData dataWithContentsOfFile:filepath]; 
    parser=[[NSXMLParser alloc]initWithData:data]; 
    parser.delegate =self; 
    [parser parse]; 
} 

ViewController.m

- (void)viewDidLoad 
{ 
    xmlParser =[[XMLParser alloc]init]; 
    NSThread *myThread =[[NSThread alloc]initWithTarget:self selector:@selector(loadXML) object:nil]; 
    [myThread start]; 
    [super viewDidLoad]; 
} 

請告訴我什麼是錯我的程序

+0

您是否使用ARC哪裏是你的應用程序後'的'裏面viewDidLoad' – 2013-03-18 05:22:09

+0

viewDidLoad'崩潰是我使用ARC和它的崩潰,當它到達nsthread實施 – Optimus 2013-03-18 05:26:59

+0

這可能是由於運行循環。你可以在'loadXML'內啓動運行循環嗎? – 2013-03-18 05:28:59

回答

2

使用此代碼爲您解決問題...

ViewController.m

- (void)viewDidLoad 
{ 
    NSThread *myThread =[[NSThread alloc]initWithTarget:self selector:@selector(doParsing) object:nil]; 
    [myThread start]; 
    [super viewDidLoad]; 
} 
-(void)doParsing 
{ 
    xmlParser =[[XMLParser alloc]init]; 
    [xmlParser loadXML]; 
} 
0

,與其建立NSThread對象你可以啓動線程使用

//performSelectorInBackground:withObject: is NSObject's method 
[self performSelectorInBackground:@selector(loadXML) withObject:nil]; 

我沒有找到任何錯誤代碼,但enable NSZombie,並看到哪個對象造成這種情況。

+0

但它仍然崩潰 – Optimus 2013-03-18 05:28:50

+0

它需要'[xmlParser performSelectorInBackground:@selector(loadXML)withObject:nil];' – rmaddy 2013-03-18 05:35:53

0

的loadXML不上的ViewController定義,以便你的線程代碼應該改爲使用XMLParser中的一個實例,而不是像這樣的自我:

XMLParser *parser = [[XMLParser alloc] init]; 
NSThread *thread = [[NSThread alloc] initWithTarget:parser selector:@selector(loadXML) object:nil]; 
[thread start]; 
0

由於蘋果推出了GCD,你可以解決它而不創建任何NSThread實例。

dispatch_async(dispatch_get_global_object(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
    [self loadXML]; 
});