制作数组的副本

时间:2012-01-25 01:09:13

标签: objective-c arrays pointers

我创建了两个可变数组 - referenceArray& stemArray,然后我用URL填充referenceArray。我想让stemArray成为referenceArray的精确副本。我收集那个制作 赋值stemArray = referenceArray;是不正确的(当我尝试这个时会发生奇怪的事情)。必须有一个更好的方法,然后简单地创建第二个循环&填充stemArray那样?指针和指针我还是不太舒服我相信这种情况是一个潜在的雷区...任何提示或建议?提前谢谢:)

    referenceArray = [NSMutableArray arrayWithCapacity:numberOfStems];
    referenceArray = [[NSMutableArray alloc] init];

    stemArray =  [NSMutableArray arrayWithCapacity:numberOfStems];
    stemArray =  [[NSMutableArray alloc] init];

for ( int i = 1; i <= numStems; i++ ) {
    NSString *soundName = [NSString stringWithFormat:@"stem-%i", i];
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:soundName ofType:@"mp3"];
    NSURL *soundFile = [[NSURL alloc] initFileURLWithPath:soundPath];   
    [referenceArray addObject:soundFile];
}

3 个答案:

答案 0 :(得分:3)

您在创建可变数组后立即覆盖指向可变数组的指针 - 为什么那些alloc / init行?如果您需要NSArray的副本,只需发送copy消息:

referenceArray = [NSMutableArray arrayWithCapacity:numberOfStems];

for ( int i = 1; i <= numStems; i++ ) {
    // Fill in referenceArray
}

stemArray = [referenceArray copy];

答案 1 :(得分:2)

为什么你不能只分配&amp;填充stemArray之后初始化referenceArray

做这样的事情:

stemArray = [[NSMutableArray alloc] initWithArray: referenceArray];

另外,摆脱你在那里做的DOUBLE alloc(即arrayWithCapacity行)。

答案 2 :(得分:1)

这里有一些问题。让我们一步一步地了解现有代码:

// You are making a new mutable array that has a starting capacity of numberOfStems and assigning it to the referenceArray variable
referenceArray = [NSMutableArray arrayWithCapacity:numberOfStems];

// You then create another new mutable array with the default capacity and re-assign the referenceArray variable.  Fortunately, the first array was created with -arrayWithCapacity: instead of -init...; thus, you aren't leaking an object
referenceArray = [[NSMutableArray alloc] init];

// Same as above
stemArray =  [NSMutableArray arrayWithCapacity:numberOfStems];
stemArray =  [[NSMutableArray alloc] init];

for ( int i = 1; i <= numStems; i++ ) {
    // This part looks fine
    NSString *soundName = [NSString stringWithFormat:@"stem-%i", i];
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:soundName ofType:@"mp3"];
    NSURL *soundFile = [[NSURL alloc] initFileURLWithPath:soundPath];   
    [referenceArray addObject:soundFile];

    // If you are in ARC, you are fine.  If non-ARC, you are leaking soundFile and need to do:
    // [soundFile release];
}

根据您的原始描述,您可能希望将stemArray声明移到最后并使用-copy或-mutableCopy:

stemArray = [referenceArray mutableCopy];  // If stemArray is defined as an NSMutableArray

或:

stemArray = [referenceArray copy];  // If stemArray is defined as an NSArray