NSMutableDictionary setObject:forKey:无法添加密钥

时间:2012-07-27 04:49:47

标签: nsmutabledictionary

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

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

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

@property (nonatomic, retain) NSMutableDictionary *studentStore;

当然在实施文件中:

@implementation School
@synthesize studentStore;

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

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

class Student具有以下属性:     @interface Student:NSObject     {         @私人的         NSString *名称; //属性         NSString *性别;         年龄;         NSString * adminNo;     }

其中newStudent具有以下值:         学生* newStudent = [[学生分配] initWithName:@“jane”性别:@“女性”年龄: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");
}  

无法打印表格中的值。相反,它会打印“printStudents failed”行。

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

1 个答案:

答案 0 :(得分:5)

您的studentStore实例变量是{em>指针到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;
}