0

我有一个运行以下方法(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

当我在调试期间将鼠标悬停在 myFloatValue 对象上时,它不包含值。相反,它说:“超出范围”。

我希望能够在不使用@property、使用 NSNumbers 以外的其他东西或其他重大更改的情况下完成这项工作,因为我只想先了解这些概念。最重要的是,我想知道我显然犯了什么错误。

4

2 回答 2

0

我可以看到几个错误:

该行@implementation应为@implementation MyClass

该函数setMyFloatValue缺少结束符],并且}应该显示为:

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

我刚刚在 Xcode 中对其进行了测试,这些更改对我有用。

于 2010-06-26T21:24:07.907 回答
0

为什么不在接口中设置属性并在实现中合成访问器?

@interface MyClass : NSObject {
  float *myFloat
}

@property (assign) float myFloat;

@end

@implementation MyClass

@synthesize myFloat;

@end
于 2010-06-26T21:28:38.533 回答