thing.h
@interface Thing : NSObject { float stuff[30]; } @property float stuff; @end
thing.m
@implementation Thing @synthesize stuff; @end
我收到错误:属性'stuff'的类型与ivar'stuff'的类型不匹配
我不想使用NSArray,因为我必须将浮点数变成NSNumber(对吗?),这对于数学运算来说是一种痛苦.
更新:我注意到类似的答案有猜测和试验答案.虽然我很欣赏非Objective-C人员的尝试,但我希望得到一个明确的答案是否有可能.
好的,我编译了以下代码,它按预期工作.
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
然后在您的其他应用程序代码中,您可以执行以下操作:
**FloatTestCode.h**
#import#import "FloatHolder.h" @interface FloatTestCode : NSObject { FloatHolder* holder; } - (void) doIt:(id)sender; @end
**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; }
属性的类型必须与它将存储的实例变量的类型相匹配,因此您可以执行类似的操作
@interface Thing : NSObject { float stuff[30]; } @property float[30] stuff; @end
它应该工作.我不会推荐它.我猜你正在寻找类似Delphi索引属性的东西.你得到的最接近的是如下.
@interface Thing : NSObject { float stuff[30]; } - (void) setStuff:(float)value atIndex:(int)index; - (float) getStuffAtIndex:(int)index; @end