I want to copy a NSMutableArray with the code below :
SectionArray *newSectionArray = [[SectionArray alloc] init];
NSMutableArray *itemsCopy = [self.sections mutableCopy];
newSectionArray.sections = [[NSMutableArray alloc] initWithArray:itemsCopy copyItems:YES];
But I have an error when I try to set an object in this new array :
[[self.sections objectAtIndex:intSection] replaceObjectAtIndex:intRow withObject:object];
[__NSArrayI replaceObjectAtIndex:withObject:]: unrecognized selector sent to instance 0x7191720
I also tried :
SectionArray *newSectionArray = [[SectionArray alloc] init];
newSectionArray.sections = [[[NSMutableArray alloc] initWithArray:itemsCopy copyItems:YES] mutableCopy];
My SectionArray class :
@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 {
...
}
@end
If I see it correctly then sections
is a mutable array, but its elements
[sections objectAtIndex:intSection]
are immutable arrays , so you get the exception at
[[sections objectAtIndex:intSection] replaceObjectAtIndex:intRow withObject:object];
The reason is that you copy the items here ( copyItems:YES
):
newSectionArray.sections = [[NSMutableArray alloc] initWithArray:itemsCopy copyItems:YES];
so even if itemsCopy
is an array of mutable arrays, the copies of these elements are immutable.
Added: For a "nested mutable copy" of your nested array you could procede as follows:
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];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.