NSMutableArray保留计数
问题描述:
target_locations[ 0] = [[CLLocation alloc] initWithLatitude : 51.50373056
longitude : 0.129986111];
[target_locations[ 0] release];
考虑上面的代码,它是保持指定对象的保留计数为1的正确方法吗?NSMutableArray保留计数
*假设ARC未激活。
答
鉴于target_locations
是NSMutableArray
,并没有启用ARC,正确的方法在这里如下:
CLLocation * newLocation = [[CLLocation alloc] initWithLatitude : 51.50373056
longitude : 0.129986111];
target_locations[0] = newLocation;
[newLocation release];
你不应该送release
到数组访问的结果,因为你不”通过该指针拥有该对象。虽然在这种情况下工作,但它的语义不正确,如果您习惯了这种情况,可能会导致问题。
另外,考虑将target_locations
重命名为targetLocations
,这与Cocoa风格一致。使用下划线使它看起来像一个普通的C数组而不是一个对象。
答案取决于'target_locations'是什么类型(尽管你不应该将'release'发送给数组中的对象)。 'NSArray'还是纯C数组? – 2012-03-27 18:49:24
想* owhnership *,而不是*保留计数*。或者,如果你必须,不要让@ bbum知道。 – 2012-03-27 18:54:20
target_locations是一个NSArray,希望bbum会发表评论... :) – Stanley 2012-03-27 19:01:28