Question

My code gives an error saying

No visible interface for 'NSMutableDictionary' declares the selector 'addObjects:forKey:'

.h

@interface ViewController : UIViewController{
    NSMutableDictionary *credtialsDictionary;
}
-(IBAction)registerlogin;
@end

.m

@implementation ViewController

-(IBAction)registerlogin{

    [credtialsDictionary addObjects:passwordFieldregister.text forKey:usernameFieldregister];
}
@end

I can't figure out why this IBAction isn't letting me add objects to the NSMutableDictionary

Was it helpful?

Solution

Because there is no instance method addObjects:forKey: in an NSMutableDictionary.

The method you are looking for is setObject:forKey:. (https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableDictionary_Class/Reference/Reference.html)

If you say why you thought the method should be addObjects:forKey: I can help you in a more generic way. But in general you want to look in Apple's documentation (like in the link above, generally just google the class name), or in look in the headers, in Xcode you can press Cmd-Shit-O and then type the name of a class and you can open the header from there.

A clue that you've got the wrong method in this case is that addObjects is plural (and forKey isn't) and you're only trying to add one object.

OTHER TIPS

Perhaps because the method name is setObject:forKey:

There is no such method addObjects:forKey:, and that wouldn't make sense as it's not meaningful to have multiple objects correspond to one key. But if you want to add multiple objects for keys in one call, it's easy enough to add something via a category if you're so inclined. An example:

#import <Foundation/Foundation.h>

@interface NSMutableDictionary (CBVAdditions)

- (void)cbvSetObjects:(NSArray *)objects forKeys:(NSArray *)keys;

@end

@implementation NSMutableDictionary (CBVAdditions)

- (void)cbvSetObjects:(NSArray *)objects forKeys:(NSArray *)keys
{
    NSDictionary *tempDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    [self addEntriesFromDictionary:tempDictionary];
}

@end

int main(int argc, char *argv[]) {
    @autoreleasepool {
        NSMutableDictionary *md = [NSMutableDictionary dictionary];
        [md cbvSetObjects:@[@"obj1", @"obj2"] forKeys:@[@"key1", @"key2"]];
        NSLog(@"md = %@", md);
    }
}

Output:

2014-05-07 15:51:03.056 Untitled[38754:507] md = { key1 = obj1; key2 = obj2; }

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top