Why is NSDictionary implemented as a class cluster?

Cluster clusters group a number of private subclasses under a common public abstract superclass. Apple's documentation uses NSNumberas an example; each of the following convenience constructors returns a separate private subclass NSNumber:

NSNumber *aChar = [NSNumber numberWithChar:’a’];
NSNumber *anInt = [NSNumber numberWithInt:1];
NSNumber *aFloat = [NSNumber numberWithFloat:1.0];
NSNumber *aDouble = [NSNumber numberWithDouble:1.0];

The motivation for using a class cluster is explained here in the documentation:

Since numbers of different types have many common features (they can be converted from one type to another and can be represented as strings, for example), they can be represented by one class. However, their storage requirements vary, so it is inefficient to represent them all in the same class.

Other examples of classes of clusters include NSString, NSData, NSArrayand NSDictionary. Based on the above explanation, I understand why NSStringand NSDatacan be implemented as class clusters. In the end, the requirements for instance storage NSStringmay differ depending on whether it was initialized with a C string or CFString.

But why NSArrayand NSDictionary? It seems that both of these classes should be used as wrappers around CFMutableArrayand CFMutableDictionary. In the end, it NSDictionarycan store something as a key or value; it does not indicate what storage requirements. So storing CFDictionary is the way to go.

For example, it NSDictionarycan be implemented as NSXDictionarybelow:

// NSXDictionary.m

@interface NSXDictionary ()
@property (nonatomic, assign) CFMutableDictionaryRef dictionary;
@end

@implementation NSXDictionary

- (instancetype)init {
    self = [super init];
    if (self) {
        _dictionary = CFDictionaryCreateMutable(NULL,
                                                0,
                                                &kCFTypeDictionaryKeyCallBacks,
                                                &kCFTypeDictionaryValueCallBacks);
    }
    return self;
}

- (void)dealloc {
    CFRelease(_dictionary);
}

- (NSUInteger)count {
    return CFDictionaryGetCount(self.dictionary);
}

- (id)objectForKey:(id)aKey {
    return CFDictionaryGetValue(self.dictionary, (__bridge const void *)(aKey));
}

@end

: NSDictionary ? NSMutableDictionary it?

+4
2

NSDictionary?

(initWithContentsOfFile, initWithObjectsAndKeys ..) , , , .

(initWithObjects: forKeys: count:, initWithDictionary, init, @{}) ( ).

/ .

. - , , .

(, , : Apple , .)

+2

, NSDictionary NSMutableDictionary:

NSMutableDictionary *mutableDict = [dict mutableCopy];

NSDictionary *dict = [mutableDict copy];

NSString/NSMutableString 
NSData/NSMutableData
NSArray/NSMutableArray

Apple:

enter image description here

:

https://developer.apple.com/library/ios/documentation/general/conceptual/CocoaEncyclopedia/ClassClusters/ClassClusters.html

0

Source: https://habr.com/ru/post/1540990/


All Articles