在iOS中定期在后台线程中运行任务
问题描述:
我是iOS新手。我正在研究应用程序需要在后台线程中运行从服务器获取数据的任务,因为我不想在主线程中锁定UI。这个任务将需要很长时间,我尝试使用NSTimer,但它仍然锁定用户界面。我的任务是在聊天屏幕中查看新消息,我需要每5秒调用一次这个任务。如果我使用NSTimer,当输入文本时,文本似乎在执行此任务时冻结一会儿。有没有办法在没有锁定UI的情况下处理这个任务。请给我一些建议。非常感谢。在iOS中定期在后台线程中运行任务
==更新代码==
- (void)performBackgroundTask
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//Do background work
if([[NSUserDefaults standardUserDefaults] boolForKey:@"LoggedIn"]) {
NSDictionary * userDictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"SessionDictionary"];
NSString *authenKey= [userDictionary valueForKey:@"authToken"];
NSString* limit = @"1000";
[[LSDataManager sharedDataManager] getLatestMessagesWithAuthKey:authenKey andLimit:limit withBlock:^ (NSDictionary* responseDict)
{
if (responseDict) {
[self loadDataFromServer:responseDict];
NSArray* lastMessageArray= nil;
//filter message data
if (self.MessagesArray.count >0) {
if (!self.isSeller) {
lastMessageArray = [self filterMessageData:self.MessagesArray withProductID:self.productID withSellerID:self.receiverID withBuyerID:self.senderID];
}
else
{
lastMessageArray = [self filterMessageData:self.MessagesArray withProductID:self.productID withSellerID:self.senderID withBuyerID:self.receiverID];
}
NSLog(@"filter array %@",lastMessageArray);
if([lastMessageArray count] >0){
//[self loadMessages:lastMessageArray];
if (self.TempdataSource == nil) {
self.TempdataSource = [NSMutableArray array];
}
else
{
[self.TempdataSource removeAllObjects];
}
self.TempdataSource = [[[ContentManager sharedManager] generateConversation:lastMessageArray withSenderID:self.senderID] mutableCopy];
}
}
}
}];
}
dispatch_async(dispatch_get_main_queue(), ^{
//Update UI
//compare 2 arrays
if ([self.TempdataSource count] == [self.dataSource count]) {
NSLog(@"both are same");
}
else{
NSLog(@"both are different");
self.dataSource = [self.TempdataSource mutableCopy];
[self refreshMessages];
}
});
});
}
答
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Thread
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
});
});
试试这个
+0
感谢您的快速回复。我试过,但它仍然是相同的 – NTNT 2014-09-19 17:14:07
答
安排使用一个NSTimer确实是正确的方式去的任务。你只需要确保你在后台线程上运行沉重的非UI代码。下面是一个例子
- (void)viewDidLoad {
[super viewDidLoad];
[self startTimedTask];
}
- (void)startTimedTask
{
NSTimer *fiveSecondTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(performBackgroundTask) userInfo:nil repeats:YES];
}
- (void)performBackgroundTask
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//Do background work
dispatch_async(dispatch_get_main_queue(), ^{
//Update UI
});
});
}
对不起。我不能给你一个回答你的问题。但我可以说使用NSTimer每5秒调用一次任务就会消耗资源,我不会建议你这么做! – eliasah 2014-09-19 17:22:12
@eliasah:谢谢。你有比它更好的解决方案吗? – NTNT 2014-09-19 17:30:01
@eliasah我不确定为什么你认为NSTimer是资源密集型的。你有任何参考?或者你只是提到每5秒钟做一次任何事情的想法? – 2014-09-19 17:46:28