==更新代码==
- (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]; } }); });}解决方法 使用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,^{ //Do background work dispatch_async(dispatch_get_main_queue(),^{ //Update UI }); });}总结
以上是内存溢出为你收集整理的在iOS中定期在后台线程中执行任务全部内容,希望文章能够帮你解决在iOS中定期在后台线程中执行任务所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)