Phil
Phil

Reputation: 3045

Subtracting a number from a number in Obj-c

This is going to probably give me a host of downvotes, but ah well. Bare in mind I'm coming from a AS3 background.

Right so, I'm in the middle of coding a display of how long it's been since something has been planted/construction started. I've got my timeToCompletion value, and my timeSincePlanting values, like this..

 //get seconds since planting/construction start
    NSDate *now = [NSDate date];
    NSTimeInterval secondsSincePlantingInterval = [now timeIntervalSinceDate:plantingDate];

    //convert to Number
    NSNumber *secondsSincePlanting = [NSNumber numberWithDouble:secondsSincePlantingInterval];

    //get template object
    NSDictionary *templateObject = [self getTemplate:kingdomObject];

    //get how long I should take (in seconds)
    NSNumber *timeToCompletion = [templateObject objectForKey:@"constructionTime"];

And everything was going swimingly until I tried to do this...

 NSNumber *timeLeft = [NSNumber numberWithInt:0];

 timeLeft = timeToCompletion - secondsSincePlanting;

Which coming from AS3 is my natural instinct, but now I realise that's probably just trying to subtract a pointer from a pointer?

So first question is, how can I do that with 2 NSNumbers? and if that's not possible and I have to use NSDecimalNumber, do I just convert everything to NSDecimalNumber and do the subtraction like that? only thing is I just need integers as I'm representing seconds, don't need to get into decimal places and all that.

Upvotes: 1

Views: 1902

Answers (2)

Hot Licks
Hot Licks

Reputation: 47729

You probably haven't dealt with object-oriented languages much. And it's easy to get confused between NSInteger (which is a "scalar" value) and NSNumber (which is an object).

An NSNumber is a "container" for a numeric value, but cannot be used in arithmetic as if it were a number. Rather, you must access the value contained in it.

Also note that saying NSNumber *timeLeft = [NSNumber numberWithInt:0]; does not initialize a numeric value to zero, but rather stores in timeLeft a pointer to an immutable NSNumber object that "wraps" the value 0. You do not then modify that object with the next statement (if it worked the way you thought), but instead you would replace one pointer with another, so the first line is useless.

Upvotes: 3

rmaddy
rmaddy

Reputation: 318814

Don't use the NSNumber objects.

NSDate *now = [NSDate date];
NSTimeInterval secondsSincePlantingInterval = [now timeIntervalSinceDate:plantingDate];

//get template object
NSDictionary *templateObject = [self getTemplate:kingdomObject];

//get how long I should take (in seconds)
NSNumber *timeToCompletion = [templateObject objectForKey:@"constructionTime"];
NSTimeInterval completionInterval = [timeToCompletion doubleValue];

NSTimeInterval timeLeft = completionInterval - secondsSincePlantingInterval;

Upvotes: 4

Related Questions