簡體   English   中英

在Obj-C中修改數組(由getter返回,例如int **)

[英]Modifying arrays (returned by getter as e.g. int**) in Obj-C

假設有一個類:

@interface FooBar : NSObject

@property(readonly, getter = _getSpace) int** space;

@end

space屬性的實現如下:

@implementation FooBar

int m_space1[256];
int m_space2[256];
int* m_space[2] = { m_space1, m_space2};

-(int **) _getSpace {
    return m_space;
}

@end

然后使用以下方法更改int [2] [256]數組是否合法:

FooBar * f = [[FooBar alloc] init];
f.space[1][120] = 0;

是。 您將返回一個指針,然后修改所指向的值。 這是完全合法的。 如果您不希望這樣做,則需要向類型添加適當的const修飾符。

不合法的是返回一個結構並直接修改該結構。


正如KennyTM在評論中提到的那樣,您的m_space{,1,2}變量是全局變量,而不是您可能想要的實例變量。 解決此問題的最簡單方法是將一個ivar塊放在@implementation ,如

@implementation FooBar {
    int m_space1[256];
    int m_space2[256];
    int* m_space[2] = { m_space1, m_space2 };
}

-(int **) _getSpace {
    return m_space;
}
@end

暫無
暫無

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

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