NSMutableDictionary setObject:forKey: fails to add key

天大地大妈咪最大 提交于 2019-12-30 11:06:59

问题


I'm sure I'm missing something in a small iPhone program I'm trying to write, but the code is simple and it compiles without any errors and so I fails to see where the error is.

I've set up a NSMutableDictionary to store students' attributes, each with a unique key. In the header file, I declare the NSMutableDictonary studentStore:

@interface School : NSObject
{
    @private
    NSMutableDictionary* studentStore;
}   

@property (nonatomic, retain) NSMutableDictionary *studentStore;

And of course in the implementation file:

@implementation School
@synthesize studentStore;

And I want to add an object into the dictionary:

- (BOOL)addStudent:(Student *)newStudent
{
    NSLog(@"adding new student");
    [studentStore setObject:newStudent forKey:newStudent.adminNo];
    return YES;
}

class Student has the attributes: @interface Student : NSObject { @private NSString* name; //attributes NSString* gender; int age; NSString* adminNo; }

where newStudent has the values: Student *newStudent = [[Student alloc] initWithName:@"jane" gender:@"female" age:16 adminNo:@"123"];

But when I look up the dictionary:

- (void)printStudents
{
    Student *student;
    for (NSString* key in studentStore)
    {
        student = [studentStore objectForKey:key];
        NSLog(@"     Admin No: %@", student.adminNo);
        NSLog(@"    Name: %@", student.name);
        NSLog(@"Gender: %@", student.gender);
    }
NSLog(@"printStudents failed");
}  

It fails to print the values in the table. Instead, it prints the line "printStudents failed".

I guess this's quite basic, but since I'm new to iOS programming I'm a bit stumped. Any help will be appreciated. Thanks.


回答1:


Your studentStore instance variable is a pointer to an NSMutableDictionary. By default, it points to nil, meaning it doesn't point to any object. You need to set it to point to an instance of NSMutableDictionary.

- (BOOL)addStudent:(Student *)newStudent
{
    NSLog(@"adding new student");
    if (studentStore == nil) {
        studentStore = [[NSMutableDictionary alloc] init];
    }
    [studentStore setObject:newStudent forKey:newStudent.adminNo];
    return YES;
}


来源:https://stackoverflow.com/questions/11681621/nsmutabledictionary-setobjectforkey-fails-to-add-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!