ios - Deep copy of object with C array -
i have object 2d c array (can't figure out how same nsarray) , need object provide deep copies of itself. i'm trying implement nscopying protocol except when trying make copy of c array can't figure out how reference self's array , copy's array. since it's not property , obj c doesn't support c array properties far know, don't know how set new copy's array.
i've tried typedefing array struct i'm using arc isn't valid solution
hopefully i'm not missing basic. thanks.
you can use ->
notation access instance variables of copied object. when making deep copy, each object in array must copied.
// define custom class store in array @interface otherclass : nsobject <nscopying> @property (nonatomic, strong) nsstring *string; @end @implementation otherclass - (id)copywithzone:(nszone *)zone { otherclass *temp = [otherclass new]; temp.string = [self.string stringbyappendingstring:@" (copy)"]; return( temp ); } - (void)dealloc { nslog( @"otherclass dealloc: %@", self.string ); } @end // define class contains c array of custom objects @interface someclass : nsobject <nscopying> { otherclass *array[5][5]; } @end @implementation someclass - (id)copywithzone:(nszone *)zone { someclass *temp = [someclass new]; ( int = 0; < 5; i++ ) ( int j = 0; j < 5; j++ ) temp->array[i][j] = [array[i][j] copy]; return( temp ); } - (void)storeobject:(otherclass *)object atrow:(int)row col:(int)col { array[row][col] = object; object.string = [nsstring stringwithformat:@"row:%d col:%d", row, col]; } - (void)dealloc { nslog( @"someclass dealloc" ); } @end // test code create, copy, , destroy objects @implementation viewcontroller - (void)viewdidload { [super viewdidload]; someclass *a = [someclass new]; ( int = 0; < 5; i++ ) ( int j = 0; j < 5; j++ ) [a storeobject:[otherclass new] atrow:i col:j]; someclass *b = [a copy]; nslog( @"releasing a" ); = nil; nslog( @"releasing b" ); b = nil; }
Comments
Post a Comment