expected method to read dictionary element not fou

2019-09-04 16:22发布

问题:

NSString *hashKey = [NSString stringWithFormat:@"%lu%lu%lu", (unsigned long)format.hash, (unsigned long)timeZone.hash, (unsigned long)locale.hash];
NSDateFormatter *formatters = [NSDate sharedDateFormatters];
NSDateFormatter *cachedDateFormatter = formatters[hashKey];

I am having trouble with this line:

NSDateFormatter *cachedDateFormatter = formatters[hashKey];

Tells me: expected method to read dictionary element not found on object of type "NSDateFormatter*"

Some context:

    + (NSMutableDictionary<NSString *, NSDateFormatter *>*)sharedDateFormatters {
    static NSMutableDictionary *dict = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dict = [NSMutableDictionary new];
    });
    return dict;
    }

回答1:

What is the return type of your sharedDateFormatters method?

What data type did you declare the formatters variable?

See the disconnect? They need to match. You can't assign an NSDictionary value to a variable of type NSDateFormatter.

Change your line to:

NSDictionary *formatters = [NSDate sharedDateFormatters];

or:

NSDictionary<NSString *, NSDateFormatter *> *formatters = [NSDate sharedDateFormatters];