button.enable没有刷新IOS

时间:2014-05-02 15:30:30

标签: ios button

我有一个UIViewController从web加载数据,这个过程大约需要15秒,所以我把我长时间运行的进程放在第二个线程上,当第二个线程完成时,我将设置按钮启用或禁用。但是当完成该过程时,该按钮不会刷新。

#import "ViewController.h"
#import "FunctionNSObject.h"

@interface ViewController ()

@end

@implementation ViewController

NSMutableArray *schoolsAvaliable;
NSDictionary *dict;
NSString *schoolNameCh, *schoolNameEn;
int schoolYear, schoolID;

- (void)viewDidLoad
{
    [super viewDidLoad];

}

-(void)viewWillAppear:(BOOL)animated
{
    //initial set the button disable
    self.button.enabled = NO;

    //2nd thread
    dispatch_queue_t downloadQueue = dispatch_queue_create("loadSchool", NULL);
    dispatch_async(downloadQueue, ^{

        //get avalible school info from JSON
        schoolsAvaliable = [FunctionNSObject loadDataFromWeb:@"http://some web service"];

        //get school year
        schoolYear = [FunctionNSObject getSchoolYear];


        if (schoolsAvaliable.count != 0)
        {

            //select the first row from array
            dict = schoolsAvaliable[0];

            //get the value from dictionary of that row
            schoolID = (int)[[dict objectForKey:@"SchoolId"] integerValue];
            schoolNameCh = [dict objectForKey:@"SchoolName"];
            schoolNameEn = [dict objectForKey:@"SchoolNameEn"];

            self.button.enabled = YES;
            [self.button setNeedsDisplay];

        }
        else
        {
            self.button.enabled = NO;
            [self.button setNeedsDisplay];

        }

        //2nd thread end then
        dispatch_async(dispatch_get_main_queue(), ^{

            //[self.pickerSchool reloadAllComponents];
            self.labelSchool.text = [NSString stringWithFormat:@"%d - %d",schoolYear,schoolYear+1];

            NSLog(@"%d",self.button.enabled);

        });

    });



}


@end

1 个答案:

答案 0 :(得分:3)

您在非主线程上调用与UI方法相关的内容。通常会导致不可预测的行为 尝试在主线程上调用与UI相关的方法,如下所示:

dispatch_async(dispatch_get_main_queue(), ^{
    self.button.enabled = YES;
});  

由于@David注意到您无需拨打[set.button setNeedsDisplay],因为调用setEnabled:方法会调用此方法。