[英]How to copy correctly a NSMutableArray?
我想用以下代碼復制NSMutableArray:
SectionArray *newSectionArray = [[SectionArray alloc] init];
NSMutableArray *itemsCopy = [self.sections mutableCopy];
newSectionArray.sections = [[NSMutableArray alloc] initWithArray:itemsCopy copyItems:YES];
但是當我嘗試在這個新數組中設置一個對象時出現錯誤:
[[self.sections objectAtIndex:intSection] replaceObjectAtIndex:intRow withObject:object];
[__NSArrayI replaceObjectAtIndex:withObject:]: unrecognized selector sent to instance 0x7191720
我也嘗試過:
SectionArray *newSectionArray = [[SectionArray alloc] init];
newSectionArray.sections = [[[NSMutableArray alloc] initWithArray:itemsCopy copyItems:YES] mutableCopy];
我的SectionArray類:
@implementation SectionArray
@synthesize sections;
@synthesize value;
- initWithSectionsForWayWithX:(int)intSections andY:(int)intRow {
NSUInteger i;
NSUInteger j;
if ((self = [self init])) {
sections = [[NSMutableArray alloc] initWithCapacity:intSections];
for (i=0; i < intSections; i++) {
NSMutableArray *a = [NSMutableArray arrayWithCapacity:intRow];
for (j=0; j < intRow; j++) {
Node * node = [[Node alloc] initNodeWithX:i andY:j andValeur:0];
[a insertObject:node atIndex:j];
}
[sections addObject:a];
}
}
return self;
}
- (void)setObjectForNode:(Node *)object andX:(int)intSection andY:(int)intRow {
[[sections objectAtIndex:intSection] replaceObjectAtIndex:intRow withObject:object];
}
- (SectionArray *) copy {
...
}
@結束
如果我正確地看到它,則sections
是可變數組,但是其元素
[sections objectAtIndex:intSection]
是不可變的數組 ,因此在
[[sections objectAtIndex:intSection] replaceObjectAtIndex:intRow withObject:object];
原因是您將項目復制到此處( copyItems:YES
):
newSectionArray.sections = [[NSMutableArray alloc] initWithArray:itemsCopy copyItems:YES];
因此,即使itemsCopy
是可變數組的數組,這些元素的副本也是不可變的。
補充:對於嵌套數組的“嵌套可變副本”,可以按以下步驟進行:
SectionArray *newSectionArray = [[SectionArray alloc] init];
newSectionArray.sections = [[NSMutableArray alloc] init];
for (NSUInteger i=0; i < [sections count]; i++) {
NSMutableArray *a = [[sections objectAtIndex:i] mutableCopy];
[newSectionArray.sections addObject:a];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.