NSMutableDictionary setObject:forKey:无法添加密钥

Rex*_*x F 2 nsmutabledictionary

我确定我在想要编写的小型iPhone程序中遗漏了一些内容,但代码很简单,编译时没有任何错误,因此我无法查看错误的位置.

我已经设置了一个NSMutableDictionary来存储学生的属性,每个属性都有一个唯一的密钥.在头文件中,我声明了NSMutableDictonary studentStore:

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

@property (nonatomic, retain) NSMutableDictionary *studentStore;
Run Code Online (Sandbox Code Playgroud)

当然在实现文件中:

@implementation School
@synthesize studentStore;
Run Code Online (Sandbox Code Playgroud)

我想在字典中添加一个对象:

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

class Student具有以下属性:@interface Student:NSObject {@private NSString*name; //属性NSString*gender; 年龄; NSString*adminNo; }

其中newStudent具有以下值:Student*newStudent = [[Student alloc] initWithName:@"jane"性别:@"female"年龄:16 adminNo:@"123"];

但是当我查阅字典时:

- (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");
}  
Run Code Online (Sandbox Code Playgroud)

它无法打印表中的值.相反,它打印"printStudents failed"行.

我想这是非常基本的,但由于我是iOS编程新手,我有点难过.任何帮助将不胜感激.谢谢.

rob*_*off 5

你的studentStore实例变量是一个指针NSMutableDictionary.默认情况下,它指向nil,这意味着它不指向任何对象.您需要将其设置为指向实例NSMutableDictionary.

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