Search code examples
ioscastingnsnumbernstimeinterval

Casting an NSTimeInterval as a NSNumber within a block


I'm having difficulty within a block with assigning an NSTimeInterval value to an NSNumber

Here is what I have so far:

[player addPeriodicTimeObserverForInterval:CMTimeMake(3, 10) queue:NULL usingBlock:^(CMTime time){
            NSTimeInterval seconds = CMTimeGetSeconds(time);
            NSNumber *lastTime = 0;
            for (NSDictionary *item in bualadhBos) {
                NSNumber *time = item[@"time"];
                if ( seconds > [time doubleValue] && seconds > [lastTime doubleValue]) {

                    lastTime = [seconds doubleValue];// this line causes difficulties
                    NSString *str = item[@"line"];
                    break;
                }; }

          }

I'm keeping track of time in an NSNumber and when the if statement is true I need to assign a new value to the variable lastTime - the problem is that I can't seem to figure out how to assign a NSTimeInterval Value contained in seconds to the variable lastTime that is of type NSNumber. I'm really confused as everything I read tells me that both are really just doubles. Any ideas?


Solution

  • You need to understand that seconds is a primitive type (NSTimeInterval - really double). lastTime is the class type NSNumber.

    To create an NSNumber from a primitive number type, you can do:

    lastTime = @(seconds);
    

    This is modern syntax for lastTime = [NSNumber numberWithDouble:seconds].

    And the line NSNumber *lastTime = 0; is technically correct but not really and it's misleading. You want:

    NSNumber *lastTime = nil;
    

    Don't confuse primitive numbers with NSNumber and objects.

    BTW - none of this is related to the use of a block.