views:

110

answers:

2

I get an error "Invalid receiver type 'NSInteger'" on this line in my implementation of a simple class:

        self.price = p; // this line throws error

Should I be specifying price as copy? More details:

header file:

@interface SafeItem : NSObject {
    NSString *name;
    NSInteger price;
    NSString *category;
    NSInteger itemid;
    BOOL hasImage;
}

@property (nonatomic,copy) NSString *name;
@property (nonatomic) NSInteger price;
@property (nonatomic,copy) NSString *category;
@property NSInteger itemid;
@property BOOL hasImage;

- (id)initWithName:(NSString*) n price:(NSInteger) p category:(NSString*) c; 

@end

implementation:

@implementation SafeItem

@synthesize name, price, category, itemid, hasImage;

- (id)initWithName:(NSString*) n price:(NSInteger) p category:(NSString*) c {
    if(self=[super init]){
        self.itemid = [SafeItem getNextId];
        self.name = [n copy];
        self.price = p; // this line throws error
        self.category = [c copy];
    }
    return self;
}
+1  A: 

No, price should not be specified as (copy). copy and retain are only used for objects, not primitive values like NSInteger.

By the way, you've specified (copy) as an attribute of the name and category properties, but you copy them again at assignment, which is redundant. Specifying (copy) for a property means that any time you set that property to a new value, copy is called automatically.

Endemic
Not just redundant, also leaky!
walkytalky
+1  A: 

No, the default assign is what you want.

Frankly, this error doesn't make sense to me -- could there be something elsewhere in the code, such as an explicit implementation of setPrice? In the meantime, grasping at straws, try omitting the accesses via self in this initialiser.

(In all four of those assignments, actually. Your use of copy is consistent with direct access to the ivars. If you are using a copy setter, you don't need to copy the argument preemptively, and doing it as you do here -- with no corresponding release -- will give you leaks. Stick to one way or the other.)

walkytalky
Thanks. I think there was something wrong in another part of the code (although there was definitely not an explicit implementation of any setters). By the way, for future readers: don't *both* remove 'self' and 'copy' (e.g. "name = n"; do either "self.name = n" or "name = [n copy]", preferably the former). I ended up removing both when trying various suggestions on this page and ended up with an EXC_BAD_ACCESS when trying to access the strings later.
unsorted