u16suzuの blog

u16suzu のブログです。

deep copy

  • deep copy するには copy methodを呼べばよい
NSMutableArray *hoge = @[@1, @2, @3].mutableCopy;
NSMutableArray *fuga = [[hoge copy] mutableCopy];

hoge[0] = @99;
NSLog(@"hoge : %@", hoge);
NSLog(@"fuga : %@", fuga);
  • result
2013-07-04 03:26:25.372 deepcopy[52245:c07] hoge : (
    99,
    2,
    3
)
2013-07-04 03:26:25.373 deepcopy[52245:c07] fuga : (
    1,
    2,
    3
)
NSMutableArray *hoge = @[@1, @2, @3].mutableCopy;
NSMutableArray *fuga = hoge;

hoge[0] = @99;
NSLog(@"hoge : %@", hoge);
NSLog(@"fuga : %@", fuga);
  • result
2013-07-04 03:29:36.201 deepcopy[52289:c07] hoge : (
    99,
    2,
    3
)
2013-07-04 03:29:36.202 deepcopy[52289:c07] fuga : (
    99,
    2,
    3
)
  • ちなみにdeep copy NSMutableArrayをdeep copyした場合 NSArrayが返る. なんてこった! 一瞬ハマった
NSMutableArray *hoge = @[@1, @2, @3].mutableCopy;
NSMutableArray *fuga = [hoge copy];    
NSLog(@"hoge : %@ %@", hoge, [hoge class]);
NSLog(@"fuga : %@ %@", fuga, [fuga class]);
  • result
2013-07-04 03:21:49.309 deepcopy[52121:c07] hoge : (
    1,
    2,
    3
) __NSArrayM
2013-07-04 03:21:49.310 deepcopy[52121:c07] fuga : (
    1,
    2,
    3
) __NSArrayI
  • とりま mutableCopy methodで NSMutableArrayに
NSMutableArray *fuga = [[hoge copy] mutableCopy];
  • また Rubyだとこんな感じ. deep copyが長い気がするよ!
# deep copy
a = [0,1,2]
b = Marshal.load(Marshal.dump(a))
b[1] = 3

p a #=>[0, 1, 2]
p b #=>[0, 3, 2]

# shallow copy
c = [0,1,2]
d = c
c[1] = 99

p c #=>[0, 99, 2]
p d #=>[0, 99, 2]