簡體   English   中英

如何使用c數組作為Objective-C對象中的實例變量?

[英]How to use c array as instance variable in an object in Objective-C?

我想在可可對象的接口塊中將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;
}

我應該在哪里分配和釋放它?

好吧,您將在分配和釋放它的位置上執行與任何實例變量相同的操作: initdealloc 訣竅是您必須使用mallocfree而不是retainrelease

至於屬性,您可以聲明它們,只需要編寫自己的訪問器和修改器即可。

同樣,請記住,為此,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。

您可以聲明它們,但是沒有C數組的“設置器”之類的東西-您不能在C中設置它們,只能將值分配給它們的索引。 您可能有一個指針的getter和setter方法,盡管這引發了您必須回答的大量內存管理問題。

如果您只需要一個int數組,而不需要管理或將其與對象本身分開分配和釋放,則只需聲明:

int arr[256];

在您的@interface聲明中,您的對象將具有一個實例變量,該變量可以容納256個整數。 如果您想要數組的int元素的getter或setter方法,則必須手動聲明和編寫它們(在屬性之前的老式方法)。

- (int)myElementOfArrAtIndex:(int)index {
  if (index >= 0 && index <= 255) {
    return (arr[index]);
  } else {
    // error handler
  }
}

等等

除非您要管理與對象分開的數組內存(例如保留數組並釋放對象,反之亦然),否則無需聲明指針。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM