NSArray :释放其对象,但保留指向它的指针

发布于 2024-09-02 04:25:30 字数 556 浏览 4 评论 0原文

我在代码中声明一个 NSArray,然后从另一个数组构建该数组。我处理我的 NSArray ,当我完成时,我想释放这些对象,但我稍后再次重用这个指向 NSAarray 的指针来执行相同的过程(从另一个数组创建数组,处理然后释放)..所以我需要保留指针。 我应该怎么办 ?

这大致是我想要做的, buildArray 正在创建并返回一个自动释放的 NSArray :

NSArray *myArray;
for (int i = 0, i < 10, i++){
  myArray = [NSArray arrayWithArray:[self buildArray]];
  // Here I process myArray

  ...

  myArray = nil; // is my guess
  }

我需要保留一个指向我的 NSArray 的指针,以便稍后在循环中重用,但是使用 [self buildArray 创建的对象发生了什么]?为了不保留未使用的对象和数组,最好做什么?

或者也许最好的解决方案就是简单地删除数组的AllObject..?

谢谢你!

I declare an NSArray in my code then building the array from another array. I process my NSArray and when I'm finished, I would like to release the objects, but I'm reusing this pointer to NSAarray again later to do the same process (creating the array from another array, process then releasing).. So I need to keep the pointer.
What should I do ?

Here is roughly what I want to do, the buildArray is creating and returning an autoreleased NSArray :

NSArray *myArray;
for (int i = 0, i < 10, i++){
  myArray = [NSArray arrayWithArray:[self buildArray]];
  // Here I process myArray

  ...

  myArray = nil; // is my guess
  }

I need to keep a pointer to my NSArray, in order to reuse later in the loop, but what is happening to the objects created with [self buildArray]? What is the best to do in order not to keep unused object and arrays ?

Or maybe the best solution is simply to removeAllObject of the array..?

Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

李不 2024-09-09 04:25:30

你不能重用 NSArray,因为它是不可变的。不过,您可以使用 NSMutableArray (它支持 -removeAllObjects)。

如果您需要保持指针,但不需要它在循环中保持不变,您可以使用

loop {
  NSArray* myArray = [self buildArray];
  ...
  // myArray = nil; // optional.
}

You can't reuse an NSArray since it's immutable. You can use an NSMutableArray (which supports -removeAllObjects) though.

If are you need is to keep the pointer, but doesn't need it constant within the loops, you could just use

loop {
  NSArray* myArray = [self buildArray];
  ...
  // myArray = nil; // optional.
}
思念满溢 2024-09-09 04:25:30

不要那样做。相反,请执行以下操作:

for (int i = 0, i < 10, i++){
    NSArray *myArray = [self buildArray]; //buildArray should return an autoreleased object
    //Process array
    //myArray goes out of scope and is autoreleased later, releasing all of its objects
}

Don't do it like that. Instead, do:

for (int i = 0, i < 10, i++){
    NSArray *myArray = [self buildArray]; //buildArray should return an autoreleased object
    //Process array
    //myArray goes out of scope and is autoreleased later, releasing all of its objects
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文