Search code examples
iphoneioscore-datansnumber

Is there some sort of convenient solution to avoid explicit NSNumber to int conversion?


I am using core data, so all my numbers are NSNumbers (since it's an old model I did not use scalar automatic conversion which seems to be available for the new core data).

So my code is full with these conversion statements:

[myNSNumberFromCoreDataObject intValue]   which is pretty annoying...

Is there any convenient solution for this or am I trapped now, since I could not use scalar core data modelling?

Edit: Ideally one could write some sort of preprocessor statement that checks these cases and automatically just substitutes this automatically - is this possible somehow?


Solution

  • You can always declare the properties on your managed objects as scalars and handle the conversion in getters/setters. Example:

    Header

    @interface MyEntity : NSManagedObject
    
    @property (nonatomic, assign, readwrite) NSUInteger count;
    
    @end
    

    Implementation

    @interface MyEntity ()
    
    @property (nonatomic, retain, readwrite) NSNumber* dbCount;
    
    @end
    
    @implementation MyEntity
    
    @dynamic dbCount;
    
    - (void)setCount:(NSUInteger)count {
        self.dbCount = [NSNumber numberWithUnsignedInteger:count];
    }
    
    - (NSUInteger)count {
        return [self.dbCount unsignedIntegerValue];
    }
    
    @end