繁体   English   中英

如何正确复制NSMutableArray?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM