Issues with Creating a New Class


#1

I am reviewing the process of creating a new class and I am stuck on the last part of the program.

Here is what I have in the Basic.h file:

#import <Foundation/Foundation.h>

@interface Basic : NSObject
{
    float cameraCost;
    float lensCost;
}

@property float cameraCost;
@property float lensCost;

-(float) totalCost;

@end

Here is what is in the Basic.m file:

#import "Basic.h"

@implementation Basic

@synthesize cameraCost, lensCost;

-(float) totalCost 
{
    return cameraCost + lensCost;
}
@end

Here is what I have in the main.m file:

#import <Foundation/Foundation.h>
#import "Basic.h"

int main (int argc, const char * argv[])
{

    @autoreleasepool {
        
        Basic *cameraKit = [[Basic alloc] init];
        
        [cameraKit cameraCost:2949.00];
        [cameraKit lensCost:1889.00];
        
        float tc = [cameraKit totalCost];
        NSLog(@"The Nikon D700 and 24-70mm f2.8 lens cost %d", tc);
        
    }
    return 0;
}

I get an error on the following lines:

They both bring an error that says: Receiver type 'Basic for instance message does not declare a method with selector ‘cameraCost’.

Please help me to see the error of my ways.

Thanks.


#2

Looks like you need to invoke setCameraCost: for setting a value; cameraCost would take no arguments and return the value.

Does the error actually say “cameraCost:” with a colon at the end? I suspect it does, because the selector “cameraCost” without a colon should exist.

Unless I’m just experiencing a brain lapse, which is entirely possible.


#3

I thought though that if you use the @property and @synthesize that it was not necessary to use set. Please clarify.

Thanks.


#4

@property + @synthesize will create two method definitions on your behalf. Assuming the property is “int aValue”, it will create methods that look like this:

-(int)aValue
{
    return self->aValue;
}

-(void)setAValue:(int)n
{
    aValue = n;
}

So when you send messages, you need to specify whether you are attempting to set or retrieve that value by sending either “setAValue:” or “aValue”.


#5

This still doesn’t address the code modification as found on page 105 of the book. Here the setWeight, etc. code is gone and in its place are the Properties options.

How does this work?

Thanks.


#6

Hah! I finally figured it out. The first to files were correct, it was the main.m file that was wrong. The @property and @synthesize code is correct however, in the main.m file is where you have to use the set property:

        [cameraKit setCameraCost:2949.00];
        [cameraKit setLensCost:1889.00];

When I did that, everything worked fine.

Thanks for the help.