2012-07-27 48 views
2

我敢肯定我在我想寫的小型iPhone程序中缺少一些東西,但代碼很簡單,它編譯時沒有任何錯誤,所以我沒有看到錯誤在哪裏。NSMutableDictionary setObject:forKey:未能添加鍵

我已經設置了一個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; 
} 

班學生有屬性: @interface學生:NSObject { @private NSString * name; //屬性 NSString * gender; int age; NSString * adminNo; }

其中newStudent具有值: 學生* newStudent = [[學生的alloc] 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編程的新手,我有點難住。任何幫助將不勝感激。謝謝。

回答

5

您的studentStore實例變量是指針NSMutableDictionary。默認情況下,它指向零,這意味着它不指向任何對象。您需要將其設置爲指向NSMutableDictionary的實例。

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