I created a bunch o开发者_如何学运维f objects and now have to write multiple lines to release them.
[Object1 release];
[Object2 release];
...
[ObjectN release];
How can I release all using one line?
There may be a way to release multiple objects using 1 line, but I don't recommend it. There is a nice way to safely release objects:
#define RELEASE_SAFELY(__POINTER) { [__POINTER release]; __POINTER = nil; }
Usage:
RELEASE_SAFELY( myObject );
#define foreach(item, array) \
for(int keep = 1, \
i= 0,\
size = sizeof (array) / sizeof *(array); \
keep && i != size; \
keep = !keep, i++) \
for(item = array + i; keep; keep = !keep)
#define RELEASE_ALL(OBJS...) ({id objs[]={OBJS}; \
foreach(id* v, objs) { RELEASE_SAFELY(*v); }})
Why not have the best of both worlds? RELEASE_SAFELY
(thanks to WrightsCS) all your objects at once:
RELEASE_ALL(Object1, Object2, Object3) // etc
There's some direct coding answers here, just wanted to add some other approaches.
You could autorelease the objects at creation time and add them to an array or other collection. The array retains the objects, and the dealloc method releases the array, the array releases all the objects. Similar to an autorelease pool.
Secondly, what is the object lifecycle? If you have a loop creating all the objects and you only need them one at a time you could create / use / dealloc or re-use in the loop, eg
for(...)
{
[[object init] alloc];
[object method];
[object release];
}
or even
[[object init] alloc];
for(...)
{
[object setProperties];
[object method];
}
[object release];
精彩评论