开发者

How can we check programmatically if an Obj-C object no longer exists (has been collected)

开发者 https://www.devze.com 2023-02-16 10:47 出处:网络
I have made a Callback class which serves as an object+selector holder for a lightweight reusable delegate model. Here\'s the code:

I have made a Callback class which serves as an object+selector holder for a lightweight reusable delegate model. Here's the code:

#import <Foundation/Foundation.h>


@interface Callback : NSObject {

    id obj;
    SEL method;
}

@property(nonatomic,assign) id obj;
@property(nonatomic,assign) SEL method;

+(Callback*) new:(id) obj1 :(SEL)method1;

@end

And the .m...

#import "Callback.h"

@implementation Callback

@synthesize obj;
@synthesize method;

+(Callback*) new:(id) obj1 :(SEL)method1{
    Callback * cb = [[Callback alloc] init];
    cb.obj= obj1;
    cb.method= method1;
    return [cb autorelease];
}

@end

The idea is I can just pass in a [Callback new:self :@selector(mymethod:)], or even an NSArray of Callbacks instead of a heavy-weight protocol implementation. Here is an example of it in action:

-(void) storeInCache:(NSArray*) contacts{
    if (contacts != nil){
        // TODO
    }
}

- (void)viewDidLoad{
    [self.service request_getContact开发者_开发技巧s:[Callback new:self :@selector(storeInCache:)]];
    // can fire off more requests on the common service class here
    // as long as I give separate Callback method references
}

I'm using it to pass through to my HTTP Service class that does a whole bunch of async method requests. Now my service class keeps a weak reference (assign) to the Callback obj it has to call when the async method returns. How can I check at that time whether the 'Callback' obj is now a zombie or not? Is my general approach terrible?


You can't check whether your Callback object has been collected. That concept doesn't make sense under garbage collection—the object won't be collected until you have no remaining ways to access the object. You can put the __weak qualifier on your instance variable, which means that as soon as the object has been collected the variable will become nil. So check for the reference being nil, not for the object itself having been collected.

If you need a collection of weakly-referenced objects, you need to use NSPointerArray, NSHashTable, or NSHashMap.

0

精彩评论

暂无评论...
验证码 换一张
取 消