I just found that there's no LinkedList implementation in Objective-C, but I need one. So I am going to use std::list(or there's a better alternative?).
My question is: what should I care about memory management under ARC and non-ARC?
You should manually take care of the memory management, since std::list is a C++ container. Or you can use NSMutableArray and treat it like a linked list, append new elements with insertObject:atIndex: for the last index, iterate through it with an iterator, removeLastObject, etc.
NSMutableArray, but from its name, I can imagine that it is implemented as holding an internal array and putting objects in that array, which is not efficient to do operations like removeLastObject or insertObject:atIndex. By manually taking care of the memory management, do you mean I will have to retain each object before I add it to the list and release all objects in the list when before I delete the list?NSMutableArray. I don't think performance will be an issue for the senario in which I am going to use a LinkedList, cause it will not hold that many objects. Thank you @Wevah, and @Alexander~You might be able to use a custom C++ smart pointer (in Objective-C++):
template<class X>
class objc_ptr {
private:
X* ptr;
public:
~objc_ptr() {
if(ptr!=NULL) [ptr release];
}
objc_ptr() {
}
objc_ptr(X* x) {
this.ptr = x;
if(x!=NULL) [x retain];
}
// TODO, copy constructor, operator= ...
};
Then you could use: std::list>
Or using boost intrusive_ptr:
void intrusive_ptr_add_ref(NSObject *x) {
[x retain];
}
void intrusive_ptr_release(NSObject *x) {
[x release];
}
std::list<boost::intrusive_ptr<NSFooBar>> list = ...;
std::listthanks to gcc/clang's Objective-C++ mode. You'll need to switch to the .mm filename extension to enable it, and you'll probably want to avoid using C++ types in your header files, or all files importing those headers will need to change to .mm as well. If the type parameters tostd::listdo not use objective-C class types, you're fine. If they are, and you aren't using ARC, you'll need to make sure you retain/release correctly. I don't know how it works with ARC but I suspect you should selectively disable ARC for your .mm files.NSMutableArray?NSMutableArrayis great, but I didn't know much about it 1 hour ago, I thought it was implemented as a raw array, which turned out to be wrong. Ridiculous Fish tells the truth.