I want to execute a for loop that looks like this:
for (id object in [[MyClass methodReturningSet] allObjects]) {
//do something
}
that methodReturningSet looks something like this:
- (NSSet *)methodReturningSet {
MyObject *object1 = [[MyObject alloc] initWithCustomInfo:info1] autorelease];
MyObject *object2 = [[MyObject alloc] initWithCustomInfo:info2] autorelease];
MyObject *object3 = [[MyObject alloc] initWithCustomInfo:info3] autorelease];
MyObject *object4 = [[MyObject alloc] initWithCustomInfo:info4] autorelease];
return [NSSet setWithObjects: object1, object2, object3, object4, nil];
}
My question, is this safe in terms of memory management?
My current understanding is that ‘object’ will be sent a release message after the completion of the run loop.
My first question is, does the entire for loop execute within one single run loop?
My second question is, does it matter if the objects get sent release messages via the autorelease pool since the array we’re looping over holds a strong reference to all the objects it contains?
hope that was clear . . . any thoughts?
Yes.
The
NSSetwill retain the objects you pass to it. After adding the objects to it, you can release your own references if you don’t need them anymore. This can either be normal release calls after adding them to the set (see below), or autorelease calls, as you did it. When you release theNSSet, it will also release (and in this case dealloc) all its objects.You could use normal release messages to like this:
That being said, consider using Automatic Reference Counting (ARC).