thing.h
@interface Thing : NSObject
{
float stuff[30];
}
@property float stuff;
@end
thing.m
@implementation Thing
@synthesize stuff;
@end
I get 错误:属性“stuff”的类型与 ivar“stuff”的类型不匹配
我不想使用 NSArray,因为我必须将浮点数转换为 NSNumber(对吗?),这做数学很痛苦。
Update:我注意到类似的答案有猜测和试验答案。虽然我很欣赏非 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 <Cocoa/Cocoa.h>
#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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)