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.
Your
studentStoreinstance variable is a pointer to anNSMutableDictionary. By default, it points to nil, meaning it doesn’t point to any object. You need to set it to point to an instance ofNSMutableDictionary.