我正在开发一个应用程序,在这个应用程序中,我在uitableview中加载xml数据,并在每5秒后调用该表视图调用解析方法并重新加载uitable以加载新数据。一切都工作正常但是应用程序在5秒后开始解析时卡住了所以我决定在解析方法中实现dispatch_async但是在应用程序崩溃之后就像5秒后应用程序重新加载一样。这是我的代码。
- (void) Parse{
previusCount = rssOutputData.count;
rssOutputData = [[NSMutableArray alloc]init];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *post =[[NSString alloc] initWithFormat:@"https://messages_%@.xml",[[NSUserDefaults standardUserDefaults] stringForKey:@"xmls_id"]];
NSData *xmlData=[[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:post]];
xmlParserObject =[[NSXMLParser alloc]initWithData:xmlData];
[xmlParserObject setDelegate:self];
dispatch_async(dispatch_get_main_queue(), ^{
[xmlParserObject parse];
[messageList reloadData];
if (previusCount != rssOutputData.count) {
NSInteger bottomRow = [rssOutputData count] - 1; // this is your count's array.
if (bottomRow >= 0) {
///////getting to latest msg/////////////
NSIndexPath *indexPathnew = [NSIndexPath indexPathForRow:bottomRow inSection:0];
[self.messageList scrollToRowAtIndexPath:indexPathnew atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
}
});
});
}
我将消息发送到xml数据文件的方法。
- (IBAction)sendClicked:(id)sender {
[messageText resignFirstResponder];
if ( [messageText.text length] > 0 ) {
NSString *rawStr;
if ([[NSUserDefaults standardUserDefaults] integerForKey:@"userType"] == 1) {
rawStr = [NSString stringWithFormat:@"data=%@&user_id=%@&session_id=%@", messageText.text, [[NSUserDefaults standardUserDefaults] stringForKey:@"therapist_id"],[[NSUserDefaults standardUserDefaults] stringForKey:@"xmls_id"]];
} else{//////In case of Patient
rawStr = [NSString stringWithFormat:@"data=%@&user_id=%@&session_id=%@", messageText.text, [[NSUserDefaults standardUserDefaults] stringForKey:@"patient_id"],[[NSUserDefaults standardUserDefaults] stringForKey:@"xmls_id"]];
}
NSData *data = [rawStr dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:@"http://do_add_message.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:data];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(@"responseData: %@", responseData);
//////////////////////
[self Parse];
}
messageText.text = @"";
}
答案 0 :(得分:0)
打印阵列。检查两次。我想你得到一个空数组。打印控制台中从服务器获取的每个对象以及您解析的对象。所以你会明白的。
<强>更新强>
只需在主线程上重新加载表数据,不要在其上解析数据。像:
dispatch_async(dispatch_get_main_queue(), ^{
[messageList reloadData];
});
将其他代码放在主线程之外。