SaldaVonSchwartz
SaldaVonSchwartz

Reputation: 3809

How do I use a core data Integer 64 property?

I want to have an Entity property in Core Data be a 64-bit integer. Since the model is going to run on iOS, and as far as I know these devices are not 64-bit, I figured that NSNumber was the way to go (core data gives you the option of objects or scalar properties for primitive types). I'm assuming that NSNumber will internally take care of keeping track of a suitable representation for 64 bits.

Now, I need to subtract 1 from this "64 bit" property in my entity at some point (in case you didn't guess, the 64 bit property is the max_id parameter in the Twitter API), but to do so, I first need to unbox the number inside the NSNumber property.

So should i get the intValue? longValue? unsignedIntValue? unsignedLongValue? long long? which one?

Upvotes: 5

Views: 5469

Answers (3)

lnafziger
lnafziger

Reputation: 25740

Since you already know the type (64 bit integer), you don't need to check for it.

To get a 64 bit integer out of a NSNumber, do one of the following:

NSInteger myInteger = [myNSNumber integerValue];
int64_t   myInteger = [myNSNumber integerValue];

In order to just add one to it, you can use something like this:

myNSNumber = [NSNumber numberWithInteger:[myNSNumber integerValue]+1]];

Note that iOS does have 64 bit data types like int64_t and NSInteger.

EDIT:
If the only reason that you are using NSNumber is to store the 64 bit integer, you can just declare the property like this in your model subclass and skip the unboxing/boxing altogether:

@property (nonatomic) int64_t myIntValue;

Note that core data does this by default if you select the Use scalar properties for primitive data types option of the Create NSManagedObject Subclass feature.

Upvotes: 8

bbarnhart
bbarnhart

Reputation: 6710

To get the C type contained in NSNumber use objCType

Example

NSNumber *myFloat = [NSNumber numberWithFloat:5.5f];
NSLog(@"%s", [myFloat objCType]);

Will print "f" as it contains a value of type float.

Also, check out @encode() which will return a C type character.

Example

NSNumber *myFloat = [NSNumber numberWithFloat:5.5f];
if (strcmp(myFloat) == @encode(float)) { 
    NSLog(@"This is a float");
}

Also

NSNumber *myFloat = [NSNumber numberWithFloat:5.5f];
CFNumberType numberType = CFNumberGetType((CFNumberRef)myFloat);

Upvotes: 0

Richard J. Ross III
Richard J. Ross III

Reputation: 55573

Try putting this in a NSNumber category:

-(int64_t) int64value
{
    if (sizeof(short) == 8)
        return [self shortValue];
    if (sizeof(int) == 8)
        return [self intValue];
    if (sizeof(long) == 8)
        return [self longValue];
    if (sizeof(long long) == 8)
        return [self longLongValue];

    return -1; // or throw an exception
}

Upvotes: 0

Related Questions