views:

33

answers:

2

I have a Class that runs the following method (a getter):

// the interface
@interface MyClass : NSObject{
    NSNumber *myFloatValue;
}

- (double)myFloatValue;
- (void)setMyFloatValue:(float)floatInput;

@end

// the implementation
@implementation
- (MyClass *)init{
    if (self = [super init]){
        myFloatValue = [[NSNumber alloc] initWithFloat:3.14];
    }
    return self;
}

// I understand that NSNumbers are non-mutable objects and can't be
// used like variables.     
// Hence I decided to make make the getter's implementation like this
- (double)myFloatValue{
    return [myFloatValue floatValue];
}
- (void)setMyFloatValue:(float)floatInput{
    if ([self myFloatValue] != floatInput){
        [myFloatValue release];
        myFloatValue = [[NSNumber alloc] initWithFloat:floatInput;
  }

@end

When I mouse over the myFloatValue object during debugging, it does not contain a value. Instead it says: "out of scope".

I would like to be able to make this work without using @property, using something other than NSNumbers, or other major changes since I just want to understand the concepts first. Most importantly, I would like to know what mistake I've apparently made.

A: 

I can see a couple of mistakes:

The line @implementation should read @implementation MyClass

The function setMyFloatValue is missing a closing ] and } —it should read:

- (void)setMyFloatValue:(float)floatInput{
    if ([self myFloatValue] != floatInput){
        [myFloatValue release];
        myFloatValue = [[NSNumber alloc] initWithFloat:floatInput];
    }
}

I've just tested it in Xcode and it works for me with these changes.

Pat Wallace
A: 

Why not just set property in interface and synthesize accessors in implementation?

@interface MyClass : NSObject {
  float *myFloat
}

@property (assign) float myFloat;

@end

@implementation MyClass

@synthesize myFloat;

@end
Eimantas