ios 从 NSArray 中删除对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13125950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove objects from NSArray
提问by Fry
I have a project with ARC.
我有一个 ARC 项目。
I have an NSArray
whit some object inside.
At certain point I need to change the object in the array.
我NSArray
里面有一些东西。在某些时候,我需要更改数组中的对象。
Whit a NSMutableArray
I'll do :
惠特一个NSMutableArray
我会做:
[array removeAllObjects];
and I'm sure that this method release all object contained in the array.
But with an NSArray I can't do that! So, my question is: if I set array to nil
and then re-initialize it, the old object contained in the array are really released from memory ?
我确信这个方法会释放数组中包含的所有对象。但是使用 NSArray 我不能这样做!所以,我的问题是:如果我将数组设置为nil
然后重新初始化它,数组中包含的旧对象是否真的从内存中释放?
array = nil;
array = [[NSArray alloc] initWithArray:newArray];
Or I need to use NSMutableArray
?
或者我需要使用NSMutableArray
?
采纳答案by Andreas Ley
You can just do this:
你可以这样做:
array = newArray;
This will cause array
to be released. When this NSArray
gets deallocated, all contained objects will be released, too.
这将导致array
被释放。当它NSArray
被释放时,所有包含的对象也将被释放。
回答by rob mayoff
The old array will be deallocated when there are no more strong references to it. If you had the only strong reference to it, then when you set array
to something else, it will be deallocated immediately.
当没有更多强引用时,旧数组将被释放。如果您拥有唯一的强引用,那么当您设置array
为其他内容时,它将立即被释放。
When the old array is deallocated, it will release all of the objects it contains. If there are no other strong references to those objects, they will also be deallocated immediately.
当旧数组被释放时,它将释放它包含的所有对象。如果没有其他对这些对象的强引用,它们也将立即被释放。
You don't have to set array = nil
before setting it to the new array.
您不必array = nil
在将其设置为新数组之前进行设置。
回答by Techie Manoj
I would suggest NSMutableArray because there would not be overhead of allocation and deallocation again
我会建议 NSMutableArray 因为不会再有分配和释放的开销