通过运行另一个对象的方法来帮助返回值的方法
我有一个运行以下方法(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 以外的东西或其他重大更改的情况下完成这项工作,因为我只想先了解这些概念。最重要的是,我想知道我明显犯了什么错误。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我可以看到一些错误:
@implementation
行应为@implementation MyClass
函数
setMyFloatValue
缺少结束]< /code> 和
}
— 它应该是这样的:我刚刚在 Xcode 中测试了它,并且它对我来说适用于这些更改。
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:I've just tested it in Xcode and it works for me with these changes.
为什么不在接口中设置属性并在实现中合成访问器?
Why not just set property in interface and synthesize accessors in implementation?