How do I know if a pointer is NSObject?

I have a pointer in an objective-C class to which I need to send messages. The pointer can potentially be anything, so I need to make sure it will respond to my messages before I post them. Here's the function I'm using to check:

int delegatePreparedForSelector(id delegate, SEL aSelector) {
    if (delegate 
        && [delegate isKindOfClass:[NSObject class]]
        && [delegate respondsToSelector:aSelector]) {
        return YES;
    }
    return NO;
}

      

The problem is that sometimes the delegate pointer is struct objc-object *

and I get an invalid access error EXC_BAD_ACCESS

when I post a message isKindOfClass

.

Is there a better test I should use to determine if a delegate will respond to my messages?

+2


source to share


3 answers


It looks like your delegate is being removed before the call, not something that is necessarily associated with this code.



Alternatively, you can provide a parameterized protocol implementation as follows, id<MyDelegateProtocol> delegate

instead of just using an empty identifier.

+5


source


Wait, do you really mean that a pointer can be anything? Like void *

pointing to a chunk of raw memory malloc or an objc_object that is not the result of an NSObject? If this is true, then there is no way to do this job safely. This is equivalent to saying "Without dereferencing this pointer, how can I know it's safe to dereference?" The only way is to have a priori knowledge that everything that passed it on to you did not give you a bad pointer.



You can try to write signal handler code to clear EXEC_BAD_ACCESS, but it will end up being slow, bad, and masking many other real errors. In reality, you have some kind of limitation on what you go through, or you need to redesign this part of your project.

+6


source


the delegate pointer pointing to the type struct objc_object causing the problem is confusing as all objects in Obj-C are of type (digging into obj-c):

struct objc_object
{
    struct objc_class *isa;
    /* extra stuff */
};

      

the is is points to a class .. some class. Thus, the object that you set as a delegate may simply not exist or point to bad memory.

-1


source







All Articles