开发者

Invalid receiver type 'NSInteger' when setting NSInteger property

开发者 https://www.devze.com 2023-01-04 10:53 出处:网络
I get an error \"Invalid receiver type \'NSInteger\'\" on this line in my implementation of a simple class:

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;
    NS开发者_开发问答Integer 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;
}


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.)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消