I have an Objective-C class whose instances can detect when they are no longer needed and destroy themselves, but I am looking for a safe way to trigger an object's self-destruction from within the object itself, without somehow "destroying the method that is calling the destruction"... My code looks roughly like this (some removed for brevity):
+ (oneway void)destroyInstance:(id)obj {
printf("Destroying.\n");
if (obj != nil) {
free(obj);
obj = nil;
}
}
- (oneway void)release {
_noLongerRequired = [self determineIfNeeded]; // BOOL retVal
if (_noLongerRequired) {
[self deallocateMemory]; // Free ivars etc (NOT oneway)
[MyClass destroyInstance:self]; // Oneway
}
}
If I call -release
, it should return instantly to the main thread (due to the oneway
).
Meanwhile, if the instance finds it is no longer needed, it should then call the oneway
class method destroyInstance:
and remove itself from the runtime. My question is, is this safe?? And have I used oneway
correctly? It seems to me there is the possibility of destroying the instance's -release
function before it returns, which could be... rather bad..?
(PS: Obviously not looking for anything to do with NSObject, etc :)
)