isMemberOfClass

  • I hate to keep belaboring the issue of identifying the class of an
    object, but consider the following code in view of Apple's
    documentation of isMemberOfClass:

    id object = [NSArray array];
    if ([object isMemberOfClass:[NSArray class]]) {
      NSLog(@"object is indeed an NSArray");
    } else {
      NSLog(@"object is not an NSArray");
    }
    Is this a bug or am I wedged?

    The code works with isKindOfClass instead of isMemberOfClass.

    Developer Documentation has this to say:
    isMemberOfClass:
    Returns a Boolean value that indicates whether the receiver is an
    instance of a given class.
    - (BOOL)isMemberOfClass:(Class)aClass

    Parameters
    aClass
    A class object representing the Objective-C class to be tested.

    Return Value
    YES if the receiver is an instance of aClass, otherwise NO.

    Discussion
    For example, in this code, isMemberOfClass: would return NO:
    NSMutableData *myData = [NSMutableData dataWithCapacity:30];
    id anArchiver = [[NSArchiver alloc]
    initForWritingWithMutableData:myData];
    if ([anArchiver isMemberOfClass:[NSCoder class]])
        ...

    -- Roland Silver <rollos...>
  • On Sep 13, 2007, at 12:34 PM, Roland Silver wrote:

    > I hate to keep belaboring the issue of identifying the class of an
    > object, but consider the following code in view of Apple's
    > documentation of isMemberOfClass:
    >
    > id object = [NSArray array];
    > if ([object isMemberOfClass:[NSArray class]]) {
    > NSLog(@"object is indeed an NSArray");
    > } else {
    > NSLog(@"object is not an NSArray");
    > }
    > Is this a bug or am I wedged?

    This is certainly not a bug.  NSArray is a class cluster :

    http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals
    /CocoaObjects/chapter_3_section_9.html


    As a result when you call [NSArray array] you don't know which of the
    classes in the cluster the returned object is a part of.

    In general, it's a very Bad Idea(tm) to rely on the identity of a
    class anyway.  It usually represents a software design flaw
    elsewhere.  Why do you need to know the class of an object?
previous month september 2007 next month
MTWTFSS
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
Go to today