0

current array is like

(a, b, c),

need to change their order, like(b,c,a),and (c,a,b),then add them to a new array, final goal is to get an array like

(( a, b, c,), (b, c, a), (c, a, b)) 

codes as following:

NSMutableArray * now = [[NSMutableArray alloc] initWithObjects:@"a", @"b", @"c", nil];
NSMutableArray * new = [[NSMutableArray alloc] init];
[new addObject:now];
NSLog(@"...new0: %@", new);

int n, i;
for (n = 0; n < 2; n ++) {
    for (i = 0; i < [now count] - 1; i ++) {
        [now exchangeObjectAtIndex:i withObjectAtIndex:i+1];
    }
    [new addObject:now];
}
NSLog(@"...new1: %@", new);

BUT, the final new1 result is (c,a,b)overwrote previous ones! What's wrong with my codes?

...new1: (
    (
    c,
    a,
    b
),
    (
    c,
    a,
    b
),
    (
    c,
    a,
    b
)

)

4

1 回答 1

0

问题是您现在使用相同的数组进行更改。这导致更改之前存储在 new 中的 now 值。这可以通过添加 now 的副本来解决,如下所示

NSMutableArray * now = [[NSMutableArray alloc] initWithObjects:@"a", @"b", @"c", nil];
    NSMutableArray * new = [[NSMutableArray alloc] init];
    [new addObject:[now copy]];
    NSLog(@"...new0: %@", new);

    int n, i;
    for (n = 0; n < 2; n ++) {
        for (i = 0; i < [now count] - 1; i ++) {
            [now exchangeObjectAtIndex:i withObjectAtIndex:i+1];
        }
        [new addObject:[now copy]];
    }
    NSLog(@"...new1: %@", new);
于 2013-06-14T08:43:53.557 回答