在c中,如果我想要一个 float 组(例如),我只需定义固定大小并分配它,并且我可以访问每个元素进行数学运算。然而,我希望能够让我的数组可变,因为它们的大小会不断增长(随着应用程序的运行,数组可以轻松超过 10000 个以上元素),并且 NSMutableArray 的想法听起来很棒。但是,(如果我理解正确的话)它只存储对象,我必须将我的数字包装在 NSNumber 中,然后将它们放入数组中。仅仅存储 float (或 double 或整数)数组似乎会产生荒谬的开销。
另一方面,我看到核心数据有 flout 属性,但我不知道如何以相同的方式访问它( array[index] )。我在这里错过了什么吗?如果所有繁重的数学工作都在固定大小的 c 数组中完成,是否有使用我没有偶然发现的基础类的方法,或者是否有像访问数组一样访问核心数据对象的方法? p>
最佳答案
你没有错过任何东西;对于 c 标量类型的数组,没有正式的 objc 接口(interface)。
简单的方法(如westsider提到的)是使用std::vector
,然后使用CF/NS-Data等机制实现序列化/反序列化。
如果你愿意,你可以将 std::vector 包装在 objc 接口(interface)中:
/* MONDoubleArray.h */
/* by using pimpl, i'm assuming you are not building everything as objc++ */
struct t_MONDoubleArray_data;
@interface MONDoubleArray : NSObject < NSCoding, NSCopying, NSMutableCopying >
{
t_MONDoubleArray_data* data;
}
- (double)doubleAtIndex;
- (void)setDoubleAtiIndex:(double)index;
- (NSUInteger)count;
/*...*/
@end
/* MONDoubleArray.mm */
struct t_MONDoubleArray_data {
std::vector<double> array;
};
@implementation MONDoubleBuffer
- (id)init
{
self = [super init];
if (0 != self) {
/* remember your c++ error handling (e.g., handle exceptions here) */
array = new t_MONDoubleArray_data;
if (0 == array) {
[self release];
return 0;
}
}
return self;
}
/*...more variants...*/
- (void)dealloc
{
delete array;
[super dealloc];
}
- (NSData *)dataRepresentationOfDoubleData { /*...*/ }
- (void)setDoubleDataFromDataRepresentation:(NSData *)data { /*...*/ }
/*...*/
@end
然后,您就可以轻松完成 objc 序列化了。
还有一种方法可以使用 CF/NS_MutableArray 作为标量,使用指针(或更窄)大小的条目:
@interface MONFloatBuffer : NSObject
{
NSMutableArray * floats;
}
@end
@implementation MONFloatBuffer
- (id)init
{
self = [super init];
if (0 != self) {
CFAllocatorRef allocator = 0; /* default */
CFIndex capacity = 0; /* resizable */
/* you could implement some of this, if you wanted */
const CFArrayCallBacks callBacks = { 0 /* version */ , 0 /* retain */ , 0 /* release */ , 0 /* copyDescription */ , 0 /* equal */ };
floats = (NSMutableArray*)CFArrayCreateMutable(allocator, capacity, &callBacks);
// now we can read/write pointer sized values to `floats`,
// and the values won't be passed to CFRetain/CFRelease.
}
return self;
}
@end
但是,如果没有自定义,它仍然无法正确反序列化自身。所以... NSPointerArray 可以更轻松地实现这一点...但是您仍然固定为指针大小的值,因此您必须自己编写它。这并不难。缺点是您最终可能会得到很多变体。
关于iphone - 在 Cocoa 中使用/存储 float 组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5045640/