如何创建浮点数数组Objective C? 可能吗? 谁能告诉我怎么能这样做?
答案 0 :(得分:22)
您可以以不同的方式创建动态数组(在运行时决定的大小,而不是编译时间),具体取决于您要使用的语言:
NSArray *array = [[NSArray alloc] initWithObjects:
[NSNumber numberWithFloat:1.0f],
[NSNumber numberWithFloat:2.0f],
[NSNumber numberWithFloat:3.0f],
nil];
...
[array release]; // If you aren't using ARC
或者,如果您想在创建后更改它,请使用NSMutableArray
:
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:0];
[array addObject:[NSNumber numberWithFloat:1.0f]];
[array addObject:[NSNumber numberWithFloat:2.0f]];
[array addObject:[NSNumber numberWithFloat:3.0f]];
...
[array replaceObjectAtIndex:1 withObject:[NSNumber numberWithFloat:99.9f]];
...
[array release]; // If you aren't using ARC
或使用new-ish Objective-C literals syntax:
NSArray *array = @[ @1.0f, @2.0f, @3.0f ];
...
[array release]; // If you aren't using ARC
float *array = (float *)malloc(sizeof(float) * 3);
array[0] = 1.0f;
array[1] = 2.0f;
array[2] = 3.0f;
...
free(array);
std::vector<float> array;
array[0] = 1.0f;
array[1] = 2.0f;
array[2] = 3.0f;
答案 1 :(得分:3)
对于动态方法,您可以使用NSNumber
对象并将其添加到NSMutableArray
,或者如果您只需要静态数组,则使用注释中的建议,或使用标准C
。
像:
NSMutableArray *yourArray = [NSMutableArray array];
float yourFloat = 5.55;
NSNumber *yourFloatNumber = [NSNumer numberWithFloat:yourFloat];
[yourArray addObject:yourFloatNumber];
然后回复:
NSNumber *yourFloatNumber = [yourArray objectAtIndex:0]
float yourFloat = [yourFloatNumber floatValue];
答案 2 :(得分:1)
答案 3 :(得分:0)
这样的事情怎么样?
@interface DoubleArray : NSObject
@property(readonly, nonatomic) NSUInteger count;
@property(readonly, nonatomic) double *buffer;
- (instancetype)init NS_UNAVAILABLE;
- (instancetype)initWithCount:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
- (double)valueAtIndex:(NSUInteger)idx;
- (void)setValue:(double)value atIndex:(NSUInteger)idx;
@end
@implementation DoubleArray
- (void)dealloc
{
if (_buffer != 0) {
free(_buffer);
}
}
- (instancetype)initWithCount:(NSUInteger)count
{
self = [super init];
if (self) {
_count = count;
_buffer = calloc(rows * columns, sizeof(double));
}
return self;
}
- (double)valueAtIndex:(NSUInteger)idx
{
return *(_buffer + idx);
}
- (void)setValue:(double)value atIndex:(NSUInteger)idx
{
*(_buffer + idx) = value;
}
@end
这是一个基本数组。您可以使用附加,索引删除等更复杂的功能对其进行扩展。