我是iOS的新手。我在应用程序上工作需要运行一个任务,在后台线程中从服务器获取数据,因为我不想在主线程中锁定UI。这个任务需要很长时间,我尝试使用NSTimer,但它仍然锁定了UI。我的任务是在聊天屏幕中查看新消息,我需要每隔5秒调用一次此任务。如果我使用NSTimer,当输入文本时,文本似乎在此任务执行时冻结片刻。有没有办法在没有锁定UI的情况下处理此任务。请给我一些建议。非常感谢。
==更新代码==
- (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];
}
});
});
}
答案 0 :(得分:34)
使用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
});
});
}
答案 1 :(得分:15)
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Thread
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
});
});
试试这个