سؤال

Currently, I have an application that is using UIRefreshControl.

I am having some issues though...

Heres my code:

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.searchDisplayController.delegate = self;
    UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
    [refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
    [self.rearTableView addSubview:refreshControl];
}


- (void)refresh:(UIRefreshControl *)refreshControl {
    [refreshControl beginRefreshing];
    [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(endRefresh:) userInfo:nil repeats:NO];
}

- (void)endRefresh:(UIRefreshControl *)refresh
{
    [refresh endRefreshing];
}

Pulling the tableview does initialize the timer but the 2 seconds are up... my app crashes and sends this message:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFTimer endRefreshing]: unrecognized selector sent to instance 0x9c093c0'

I am confused :(

هل كانت مفيدة؟

المحلول

Issue:

This issue occurs because:

[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(endRefresh:) userInfo:nil repeats:NO];

You are added the endRefresh: as the selector for the timer. So the parameter for the endRefresh: method will be a NSTimer not UIRefreshControl.

The actual method signature will look like:

- (void)endRefresh:(NSTimer *)refresh
{
   //your code
}

You are calling the endRefreshing NSTimer object, that's why the crash occurs.

Declaring like:

- (void)endRefresh:(UIRefreshControl *)refresh

Just typecast NSTimer object to UIRefreshControl nothing more.

It is equivalent to:

- (void)endRefresh:(NSTimer *)timer
{
   UIRefreshControl *refresh = (UIRefreshControl *)timer;
   [refresh endRefreshing];
}

Solution 1:

Declare UIRefreshControl as a property and use it.

Solution 2:

Change your methods like:

- (void)refresh:(UIRefreshControl *)refreshControl
{
    [refreshControl beginRefreshing];
    [self performSelector:@selector(endRefresh:) withObject:refreshControl afterDelay:2.0f];
}

- (void)endRefresh:(UIRefreshControl *)refresh
{
    [refresh performSelectorOnMainThread:@selector(endRefreshing) withObject:nil waitUntilDone:NO];
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top