2013-03-30 63 views
0

我想一個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 { 
    ... 
} 

@end

+0

顯示SectionArray類 –

+0

我認爲SectionArray不可變。 –

+0

我在我的文章中添加sectionArray類。 – cmii

回答

0

如果我正確地看到它,然後sections是一個可變數組,但它的元素

[sections objectAtIndex:intSection] 

不變陣列,讓你

[[sections objectAtIndex:intSection] replaceObjectAtIndex:intRow withObject:object]; 

得到異常原因是你拷貝這裏的物品(copyItems:YES):

newSectionArray.sections = [[NSMutableArray alloc] initWithArray:itemsCopy copyItems:YES]; 

所以即使itemsCopy是一個可變數組的數組,這些元素的副本是不可變的。

補充:爲了您的嵌套數組的「嵌套式可變副本」你可以PROCEDE如下:

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]; 
} 
+0

如何解決這個問題? – cmii

+0

@cmi:看到我更新的答案,我希望有幫助。它的工作原理是 –

+0

。多謝! – cmii

相關問題