Why does NSDictionary report an unusual class name?

后端 未结 5 1038
孤独总比滥情好
孤独总比滥情好 2021-02-10 09:59
NSDictionary *dict = [NSDictionary dictionary];
NSLog(@\"%@\", NSStringFromClass([dict class])); 

This code prints \"__NSDictionary0\".

For my

相关标签:
5条回答
  • 2021-02-10 10:21

    For an NSDictionary mutability test, could't you just to a 'respondsToSelector' for a method that only an NSMutableDictionary would have, like addObject:ForKey:?

    0 讨论(0)
  • 2021-02-10 10:25

    NSDictionary is a class cluster. Read about them here:

    Cocoa Fundamentals Guide

    As the "actual" class itself is private, no, it is not safe to depend on this.

    If you need to know if your class is really an NSDictionary or not, use [dict isKindOfClass:[NSDictionary class]];

    0 讨论(0)
  • 2021-02-10 10:34

    So, basically, you need to know if you are having an NSMutableDictionary or a bare NSDictionary beforehand. Or don't need to know. Or create an NSMutableDictionary from your object (NSDictionary or NSMutableDictionary)?

    What was the question originally for?

    0 讨论(0)
  • 2021-02-10 10:35

    NSDictionary is a class cluster, as Gendolkari said and Class Clusters are documented.

    And, no, you can't depend on the exact identity of the private subclass.

    You should certainly be able to do the following to determine if it is a dictionary or not:

    [myThingaMaHoover isKindOfClass: [NSDictionary class]];
    

    Or, at the least, that it is a dictionary as implemented as a part of the NSDictinoary class cluster.

    What you can't do is use isKindOfClass: or isMemberOfClass: to determine whether or not a dictionary (or string, array, or set) is mutable. Consider:

    NSDictionary *d = [NSDictionary dictionaryWithObject: [[NSObject new] autorelease] forKey: @"Bob"];
    NSMutableDictionary *m = [NSMutableDictionary dictionaryWithObject: [[NSObject new] autorelease] forKey: @"Bob"];
    NSLog(@"d class: %@ %@ %@", [d class], [d superclass], [[d superclass] superclass]);
    NSLog(@"m class: %@ %@ %@", [m class], [m superclass], [[m superclass] superclass]);
    

    This outputs:

    d class: NSCFDictionary NSMutableDictionary NSDictionary
    m class: NSCFDictionary NSMutableDictionary NSDictionary
    

    d and m are both instances of NSCFDictionary which inherits from NSMutableDictionary (which inherits from NSDictionary).

    0 讨论(0)
  • 2021-02-10 10:45

    If you want to test for mutability, your best bet would probably be conformsToProtocol: @protocol(NSMutableCopying)

    0 讨论(0)
提交回复
热议问题