2
如果您有一個目標c中的方法使用可變對象構建數組或字典,那麼您應該複製該對象還是返回可變版本?這可能是一個意見,但我從來沒有能夠下定決心。這裏有兩個例子來說明我在說什麼:返回可變或複製
- (NSArray *)myMeth
{
NSMutableArray *mutableArray = [NSMutableArray array];
for (int i=0; i<10; i++) {
[mutableArray addObject:[NSNumber numberWithInt:i]];
}
return mutableArray;//in order for calling code to modify this without warnings, it would have to cast it
}
- (NSArray *)myMeth
{
NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
for (int i=0; i<10; i++) {
[mutableArray addObject:[NSNumber numberWithInt:i]];
}
NSArray *array = [[mutableArray copy] autorelease];
[mutableArray release];
return array;//there is no way to modify this
}
我記得之前被問過;我認爲一般來說,可以直接從可以簡單創建並返回數組的方法返回可變數組(因爲您的對象本身並不保留它,也不在乎內容是否更改)。如果你要退回伊娃,你一定要在退貨時複製/自動釋放。 如果你的方法說它返回一個'NSArray *',調用者應該把它看作是不可變的,即使它不是(儘管我確定有時不會發生這種情況)。 – Wevah 2010-06-26 16:22:41