i have lines of code:
- (void)redrawgraphwitharray:(nsarray *)array { _graphview.graphpoints = [array copy]; [_graphview setneedsdisplay]; }
graphpoints nsarray too.
if use
_graphview.graphpoints = array;
the graph looks same , there's no problem.
i wanna know difference between
_graphview.graphpoints = [array copy]
,
_graphview.graphpoints = array;
thanks.
_graphview.graphpoints = array;
assigns graphpoints same array original object. you're creating pointer exact same memory. instance, happen:
nsmutablearray *array = [[nsmutablearray alloc] init]; array[0] = @{@"x": @1, @"y": @2}; array[1] = @{@"x": @1, @"y": @3}; _graphview.graphpoints = array; // let's make changes original array // note used nsmutablearray explain differences between // 2 assignment types. array[0] = @{@"x": @1, @"y": @1}; // nsarray wouldn't able array[1][@"y"] = @5; // can still happen // happens graphpoints? _graphview.graphpoints[0]; // <== {x: 1, y: 1} _graphview.graphpoints[1]; // <== {x: 1, y: 5}
in case, graphpoints
points exact same object array
2 remain same. it's not illustrated in code example, it's important remember "sameness" points in both directions, making changes graphpoints
change array
.
on other hand, [array copy]
creates new array object copy of original, above code have different result:
nsmutablearray *array = [[nsmutablearray alloc] init]; array[0] = @{@"x": @1, @"y": @2}; array[1] = @{@"x": @1, @"y": @3}; _graphview.graphpoints = [array copy]; // let's make same changes original array array[0] = @{@"x": @1, @"y": @1}; array[1][@"y"] = @5; // happens graphpoints? _graphview.graphpoints[0]; // <== {x: 1, y: 2} _graphview.graphpoints[1]; // <== {x: 1, y: 5}
the first object didn't change in graphpoints
, because wrote whole new object array
. since graphpoints
copy, didn't affected.
however, second object did change, because didn't write new object array
, instead modified existing object, contained both arrays. illustrates important subtlety object copying. what's known "shallow" copy, means container gets copied, contents not. end 2 arrays, 1 set of contained objects.
there relatively straightforward ways copy of contained objects making sure contained objects implement nscopying
protocol (if you're using foundation
classes nsdictionary
, nsarray
, nsnumber
, nsstring
, don't need worry, done you) , using - initwitharray:copyitems:
initializer on nsarray
. create shallow copies of contained objects, there lots of info available how implement full "deep" copy, should need so.
Comments
Post a Comment