Search code examples
iosobjective-cnstimernsinvocation

iOS - Timer invocation issue


I wanted to invoke a method if the timer is expired, but the method does not get invoked. Not sure what is going wrong. Any suggestions?

Being called:

- (void)messageSendingReply:(id)messageID
{
    //Do something.
}

Calling the above:

- (void)sendingMessageTimer_Start:(int64_t)sendingMsgID Time:(NSTimeInterval)replyDelay {

    NSMethodSignature *sig = [self methodSignatureForSelector:@selector(messageSendingReply:)];


    if (sig)
    {

        NSInvocation* invo = [NSInvocation invocationWithMethodSignature:sig];
        [invo setTarget:self];
        [invo setSelector:@selector(messageSendingReply:)];
        id obj= [NSNumber numberWithLongLong:sendingMsgID];
        [invo setArgument:&obj atIndex:0];
        [invo retainArguments];

        [self.replyTimerDic setValue:[NSTimer scheduledTimerWithTimeInterval:replyDelay invocation:invo repeats:NO] forKey:[NSString stringWithFormat:@"%qi",sendingMsgID]];

    }

}

Solution

  • I resolved it by adding the timer on current run loop and run. Thanks.

    if (sig)
    {
        NSInvocation* invo = [NSInvocation invocationWithMethodSignature:sig];
        [invo setTarget:self];
        [invo setSelector:@selector(messageSendingReply:)];
        id obj= [NSNumber numberWithLongLong:sendingMsgID];
        [invo setArgument:&obj atIndex:0];
        [invo retainArguments];
    
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:replyDelay invocation:invo repeats:NO];
    
        [self.replyTimerDic setValue:timer forKey:[NSString stringWithFormat:@"%qi",sendingMsgID]];
    
        NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
        [runLoop addTimer:timer forMode:NSRunLoopCommonModes];
        [runLoop run];
    }