Search code examples
objective-cnsmanagedobject

Differences between@property (nonatomic) double longitude &@property (nonatomic, retain) NSNumber * longitude;


I set Entity longitude as double and create NSManagedObject Subclass. In properties.h I got the longitude as

 @property (nonatomic) double longitude;

Then a error jumps out as

Assigning to 'double' from incompatible type 'NSNumber *'

in below line

photo.longitude=@([photoDictionary[FLICKR_LONGITUDE] doubleValue]);

Things didn't get well until I change the code into

@property (nonatomic, retain) NSNumber * longitude;

I`m confused about these.

Any advice would be appreciative.


Solution

  • As per the documentation:

    NSNumber is a subclass of NSValue that offers a value as any C scalar (numeric) type. It defines a set of methods specifically for setting and accessing the value as a signed or unsigned char, short int, int, long int, long long int, float, or double or as a BOOL.

    I.e. NSNumber is a class that encapsulates a primitive value (such as a double in your case) and provides an object oriented interface (among other things).

    What you are trying to do is to assign an object of type NSNumber to a property of type double (hence the error you are shown).

    However, with this code...

    photo.longitude=@([photoDictionary[FLICKR_LONGITUDE] doubleValue]);
    

    ... you obtain a double from photoDictionary by calling doubleValue on the NSNumber returned and then you re-wrap it in an NSNumber using the NSNumber literal: @(...). If you remoVe the literal and simply assign [photoDictionary[FLICKR_LONGITUDE] doubleValue] directly to photo.longitude you should be fine.