问题
let's say if you have class doing something on some other thread. And has delegate of its own.
@protocol XRequestDelegate;
@interface XRequest : NSObject {
id<XRequestDelegate> delegate;
}
@property (nonatomic, retain) id<XRequestDelegate> delegate;
- (void) doSomething;
@end
@protocol XRequestDelegate <NSObject>
- (void)request:(XRequest *)request didFinish:(id)object;
- (void)request:(XRequest *)request didFailWithError:(NSError*)error;
@end
doSomething eventually calls either request:didFinish:
or request:didFailWithError:
and lets use this class in our object;
- (void)doRequest
{
XRequest *request = [[XRequest alloc] init];
[request setDelegate:self];
[request doSomething];
}
- (void)request:(XRequest *)request didFinish:(id)object
{
// Use object whatever you want
[request release];
}
- (void)request:(XRequest *)request didFailWithError:(NSError *)error
{
//Log Error
[request release];
}
we have an instance of XRequest
allocated and eventually released in methods.
Can we say this is a wrong way of memory management. Should we expand the scope of XRequest
object?
回答1:
Apple's fundamental rule of memory management states:
You only release or autorelease objects you own.
I think in this case, you would not be breaking that rule, since your delegate is the object that allocated the request. You do mention multiple threads, however, and the best practice there is to have one object per thread (don't allocate the request on one thread and release it on another).
回答2:
I have seen apple examples do it that way (I believe it is one of the media player ones) but I would say that is a wrong way of doing memory management. What happens if the class referencing XRequest
gets deallocated before XRequest
finishes? How do you prevent any further delegate calls or release it.
What you want to do is retain the request in an ivar and then remove its delegate and release it and set it to nil on the finish/fail methods and in -(void)dealloc
.
来源:https://stackoverflow.com/questions/5585937/releasing-a-parameter