【问题标题】:What happens in cocoa touch when the objects that were added in an array are released?当添加到数组中的对象被释放时,cocoa touch 会发生什么?
【发布时间】:2011-11-09 22:07:36
【问题描述】:

我有以下来自 Xcode (Cocoa touch) 的代码:

//Here, the class Vector2 is a class I made that stores an x value and a y value (As with XNA).

Vector2 *pointOne = [[Vector2 alloc] initWithX:170 Y:224];
Vector2 *pointTwo = [[Vector2 alloc] initWithX:193 Y:173];
Vector2 *pointThree = [[Vector2 alloc] initWithX:233 Y:67];
Vector2 *pointFour = [[Vector2 alloc] initWithX:276 Y:164];
Vector2 *pointFive = [[Vector2 alloc] initWithX:299 Y:226];
Vector2 *pointSix = [[Vector2 alloc] initWithX:276 Y:168];
Vector2 *pointSeven = [[Vector2 alloc] initWithX:193 Y:173];

//Add positions to array

NSArray * points = [[NSArray alloc] initWithObjects:pointOne, pointTwo, pointThree, pointFour, pointFive, pointSix, pointSeven, nil];

//release memory for Vector2's

[pointOne release];
[pointTwo release];
[pointThree release];
[pointFour release];
[pointFive release];
[pointSix release];
[pointSeven release];

我的问题是,释放 Vector2 是否会使数组对象也变为空?

【问题讨论】:

    标签: objective-c arrays xcode cocoa-touch memory-management


    【解决方案1】:

    NSArray 保留其内容*。因此,每个Vector2 在添加时都会被保留,然后在从数组中删除或数组被销毁时释放。

    在 OP 的上下文中,您可以在对它调用 release 之后仍然使用 pointOne(因为该数组包含对对象的引用),但不建议这样做,因为无论谁阅读您的程序会读两遍,可能想要更正它。这一点尤其重要,因为数组语义是微不足道的。在处理另一个对象时,它可能会复制参数或完全做其他事情。

    您应该在释放 ivar 之前使用 pointOne,或者从数组中访问它。

    *默认情况下。您实际上可以使用 CoreFoundation api 创建一个不保留其内容的 NSArray。

    【讨论】:

    • 所以这段代码不会让数组的内容被清除?
    【解决方案2】:

    数组中的向量是安全的。这段代码看起来不错,而且正确。

    数组保留了你给它的对象,所以它有自己的“所有权”。数组释放的时候,会释放当时里面的所有对象。

    【讨论】:

      猜你喜欢
      • 2011-11-27
      • 1970-01-01
      • 2011-08-25
      • 1970-01-01
      • 2016-01-15
      • 1970-01-01
      • 1970-01-01
      • 2010-10-14
      • 2022-06-27
      相关资源
      最近更新 更多