Vancore
Vancore

Reputation: 697

How to access object for id

Hiho code-friends,

I created a NSMutableDictionary "_favDictionary" with picture-data inside. I am getting the key from my current cell from a collection-view, which contains an integer named "key".

FLAMainCell *cell = (FLAMainCell *) sender.view;
NSUInteger *key = cell.key;

NSString *inStr = [NSString stringWithFormat:@"%lu", (unsigned long)key];
_favDictionary[inStr] = storeImage;  


- (UIImage *)getFavouriteImages:(NSInteger)index{
    return _favDictionary[index];
}

I am a beginner in objective-c and I could not find a possibility to access my dictionary with an integer value like in my method "getFavouriteImages". The error I am getting says "NSMutableDictionary doesn't respond to ObjectAtIndexedSubscript".

Can someone tell me how I can access my dictionary via an integer?

Upvotes: 1

Views: 68

Answers (1)

Sulthan
Sulthan

Reputation: 130092

First of all, if you are indexing only by integers, you could use a NSArray.

If you want to use a NSDictionary, you don't have to convert integers to strings, you can use NSNumber instead.

FLAMainCell *cell = (FLAMainCell *) sender.view;
NSUInteger *key = cell.key;

NSNumber *inNumber = @(key);
_favDictionary[inNumber] = storeImage;  

- (UIImage *)getFavouriteImages:(NSInteger)index{
    return _favDictionary[@(index)];
}

If you want to use strings, then you have to convert index to a NSString too, before indexing:

- (UIImage *)getFavouriteImages:(NSInteger)index{
    NSString *stringIndex = [NSString stringWithFormat:@"%@", @(index)];
    return _favDictionary[stringIndex];
}

Upvotes: 2

Related Questions