NSMutableDictionary不检索对象

时间:2012-02-09 16:24:57

标签: objective-c ios xcode

EmployeesArray = [[NSMutableArray alloc] initWithCapacity:100];
    Employees *Emp1 = [[Employees alloc] init];    
    Emp1.Number = 1;
    Emp1.Name = @"Jamal";
    Emp1.Age = 16;
    Emp1.Gender = @"Male";
  [EmployeesArray addObject:Emp1];
 [Dic1 setValue:Emp1 forKey:@"A"];

- (IBAction)Retrieve:(id)sender {

  Employees *objEmp2 = [Dic1 valueForKey:@"A"];
    printf(objEmp2.Name);

}

为什么这段代码不能检索名字?和错误出现??

3 个答案:

答案 0 :(得分:2)

有三件事可能会有所帮助。

  1. 使用-setObject:forKey:代替-setValue:forKey 因为您使用自定义类,所以请使用objectForKey而不是valueForKey
  2. 通常,使用objective-c样式-NSLog()代替c样式代码会更容易。
  3. 确保已导入包含Employees类定义的头文件,而不是仅将其用作当前.m文件的转发类。

答案 1 :(得分:2)

您需要使用setObject:forKeyobjectForKey:方法,而不是setValue:forKey:valueForKey:

答案 2 :(得分:2)

您是否初始化了Dic1字典?

// try doing this
Dic1 = [[NSMutableDictionary alloc] init];

EmployeesArray = [[NSMutableArray alloc] initWithCapacity:100];
    Employees *Emp1 = [[Employees alloc] init];    
    Emp1.Number = 1;
    Emp1.Name = @"Jamal";
    Emp1.Age = 16;
    Emp1.Gender = @"Male";
  [EmployeesArray addObject:Emp1];
 [Dic1 setObject:Emp1 forKey:@"A"];

- (IBAction)Retrieve:(id)sender {

  Employees *objEmp2 = [Dic1 objectForKey:@"A"];
    printf(objEmp2.Name);

}