我想在 Cocoa 对象的接口块中将 ac 数组声明为实例变量(例如 int arr[256])。我知道@property 不支持 c 数组,但是如何手动为 c 数组添加 getter 和 setter,我应该在哪里分配和释放它?
任何输入将不胜感激。我真的不想使用 NSMutableArray 来访问 int 值。
我想在 Cocoa 对象的接口块中将 ac 数组声明为实例变量(例如 int arr[256])。我知道@property 不支持 c 数组,但是如何手动为 c 数组添加 getter 和 setter,我应该在哪里分配和释放它?
任何输入将不胜感激。我真的不想使用 NSMutableArray 来访问 int 值。
您可以使用结构来包装数组。这可能是允许通过赋值复制数组的一个例外。这种方法的好处是不需要显式分配或释放内存。
typedef struct
{
int data[256];
} MyInts;
@interface MyClass : NSObject
{
MyInts ints;
}
- (MyInts) ints;
- (void) setInts:(MyInts) someInts;
@end
@implementation MyClass
- (MyInts) ints
{
return ints;
}
- (void) setInts:(MyInts) someInts
{
ints = someInts;
}
@end
int main(void)
{
MyInts ints = {{0}};
ints.data[4] = 345;
ints.data[5] = 123;
ints.data[6] = 101;
MyClass *someObj = [[MyClass alloc] init];
[someObj setInts:ints]; // provide the ints to the object
[someObj mutateTheInts]; // have object do something with them
ints = [someObj ints]; // get them back
return 0;
}
我应该在哪里分配和释放它?
好吧,您将在与任何实例变量相同的位置分配和释放它: ininit
和dealloc
. 诀窍是你必须使用malloc
andfree
而不是retain
and release
。
至于属性,您可以声明它们,您只需要编写自己的访问器和修改器。
另外,请记住,为此目的,C 数组就像一个指针。
话虽如此,您可能会执行以下操作:
@interface MyClass : NSObject
{
int *arr;
}
@property int *arr;
@end
@implementation MyClass
#import <stdlib.h>
@dynamic arr;
- (id)init
{
if ((self = [super init])) {
arr = malloc(sizeof(int) * 256);
}
return self;
}
- (void)dealloc
{
free(arr);
[super dealloc];
}
- (int *)arr
{
// Return a copy -- don't want the caller to deallocate
// our instance variable, or alter it without our knowledge!
// Also note that this will leak unless the caller releases it.
int *arrCpy = malloc(sizeof(int) * 256);
memcpy(arrCpy, arr, sizeof(int) * 256);
return arrCpy;
}
- (void)setArr:(int *)anArr
{
if (arr != anArr) {
free(arr);
// Again, copy the data so that the caller can't
// change the values of specific ints without
// out knowledge.
int *anArrCpy = malloc(sizeof(int) * 256);
memcpy(anArrCpy, anArr, sizeof(int) * 256);
arr = anArrCpy;
}
}
您可以做一些更好的错误检查,并且代码可以稍微修饰一下,但这就是要点。
您还可以使用 CoreFoundation 数据类型,它们基本上只是 C 原语和结构;内存管理会更容易一些,但它也不是您要求的“直接 C”整数。
不过,老实说,我认为你最好只使用 NSNumber 对象的 NSArray —— 内存管理会容易得多,而且它可能与其他 Objective-C 框架更兼容。它也将更加独立于平台,因为 Cocoa 考虑了 64 位与 32 位环境以及字节序及其数据类型。至少,您应该使用 NSInteger 而不是 int。
如果您只想要一个整数数组,并且不需要管理,或者分配和释放它与对象本身分开,那么只需声明:
int arr[256];
在您的@interface 声明中,您的对象将有一个可容纳 256 个整数的实例变量。如果您想要数组的 int 元素的 getter 或 setter,则必须手动声明和编写它们(属性之前的老式方式)。
- (int)myElementOfArrAtIndex:(int)index {
if (index >= 0 && index <= 255) {
return (arr[index]);
} else {
// error handler
}
}
等等
除非您想将数组的内存与对象分开管理(例如,保留数组并释放对象,反之亦然),否则无需声明指针。
您可以声明它们,但没有 C 数组的“设置器”之类的东西 - 您不能在 C 中设置它们,只能为它们的索引分配值。您可以为指针使用 getter 和 setter,但这会引发您必须回答的大量内存管理问题。