在 Objective-C 中,我可以在浮点数 c 数组上声明 @property 吗? [英] In Objective-C, can I declare @property on a c-array of floats?
问题描述
东西.h
@interface Thing : NSObject
{
float stuff[30];
}
@property float stuff;
@end
东西.m
@implementation Thing
@synthesize stuff;
@end
我收到错误:属性stuff"的类型与 ivarstuff"的类型不匹配
我不想使用 NSArray,因为我必须将浮点数转换为 NSNumbers(对吗?),用它做数学很麻烦.
I don't want to use an NSArray because I'd have to make the floats into NSNumbers (right?) and that's a pain to do math with.
更新:我注意到类似的答案有猜测和试用答案.虽然我很欣赏非 Objective-C 人员的尝试,但我希望得到一个明确的答案,无论是否可行.
Update: I've noticed similar answers had guesses and trial answers. While I appreciate the attempts by non-Objective-C folks, I'm hoping for a definitive answer whether it's possible or not.
推荐答案
好的,我已经编译了以下代码,它按预期工作.
OK, I have compiled up the following code at it works as expected.
FloatHolder.h
@interface FloatHolder : NSObject {
int _count;
float* _values;
}
- (id) initWithCount:(int)count;
// possibly look into this for making access shorter
// http://vgable.com/blog/2009/05/15/concise-nsdictionary-and-nsarray-lookup/
- (float)getValueAtIndex:(int)index;
- (void)setValue:(float)value atIndex:(int)index;
@property(readonly) int count;
@property(readonly) float* values; // allows direct unsafe access to the values
@end
FloatHolder.m
#import "FloatHolder.h"
@implementation FloatHolder
@synthesize count = _count;
@synthesize values = _values;
- (id) initWithCount:(int)count {
self = [super init];
if (self != nil) {
_count = count;
_values = malloc(sizeof(float)*count);
}
return self;
}
- (void) dealloc
{
free(_values);
[super dealloc];
}
- (float)getValueAtIndex:(int)index {
if(index<0 || index>=_count) {
@throw [NSException exceptionWithName: @"Exception" reason: @"Index out of bounds" userInfo: nil];
}
return _values[index];
}
- (void)setValue:(float)value atIndex:(int)index {
if(index<0 || index>=_count) {
@throw [NSException exceptionWithName: @"Exception" reason: @"Index out of bounds" userInfo: nil];
}
_values[index] = value;
}
@end
然后在您的其他应用程序代码中,您可以执行以下操作:
then in your other application code you can do something like the following:
** FloatTestCode.h **
** FloatTestCode.h **
#import <Cocoa/Cocoa.h>
#import "FloatHolder.h"
@interface FloatTestCode : NSObject {
FloatHolder* holder;
}
- (void) doIt:(id)sender;
@end
** FloatTestCode.m **
** FloatTestCode.m **
#import "FloatTestCode.h"
@implementation FloatTestCode
- (id) init
{
self = [super init];
if (self != nil) {
holder = [[[FloatHolder alloc] initWithCount: 10] retain];
}
return self;
}
- (void) dealloc
{
[holder release];
[super dealloc];
}
- (void) doIt:(id)sender {
holder.values[1] = 10;
}
这篇关于在 Objective-C 中,我可以在浮点数 c 数组上声明 @property 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!