0

从我读过的内容中NSMutableArray添加了对象。

如何Student从给定位置打印对象变量而不将对象转换为Student.

我正在寻找类似ArrayList<Student>Java 的东西,所以我可以轻松地打印ArrayList.get(i).getName, ArrayList.get(i).getPrice.

    StudentRepository* myStudentRepo = [[StudentRepository alloc]init];

    Student* myStudent = [[Student alloc]init];

    myStudent.name = @"John";

    // add a Student to the NSMutableArray
    [myStudentRepo.studentRepository addObject:myStudent];

    NSLog(@"Value: %@", myStudentRepo.studentRepository);

    for(Student* myStudentItem in myStudentRepo.studentRepository)
    {
        NSLog(@"Value: %@", myStudentItem.name);
    }

    // print the Student from a given position
    NSLog(@"Value: %@", [(Student*)[myStudentRepo.studentRepository objectAtIndex:0] name]);
4

5 回答 5

2

您发布的代码按原样很好。Objective-C / Cocoa 中没有与 Java 的类型化集合等效的东西。您需要转换结果。

实际上,您可以做一个小技巧:

NSLog(@"Value: %@", [myStudentRepo.studentRepository[0] valueForKey:@"name"]);
于 2013-02-21T21:31:27.903 回答
1

您可以使用 KVC(键值编码)来访问对象的属性而无需强制转换:

[[myStudentRepo.studentRepository objectAtIndex:0] valueForKey:@"name"];

请参阅:https ://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueCoding/Articles/BasicPrinciples.html#//apple_ref/doc/uid/20002170-BAJEAIEE

于 2013-02-21T21:32:48.420 回答
1

您可以覆盖descriptiondebugDescription在您的Student班级中:

由于我不是您的学生的组成,请允许以下直截了当的示例:

// could also be -(NSString*)debugDescription    
- (NSString *)description {
      return [NSString stringWithFormat:@"Prop1: %@ \nIntVal1: %d\nfloatVal1 = %3.2f", self.prop1, self.intVal1, self.floatval1];
}

但是,对于大型复杂的对象,这会变得乏味。

于 2013-02-21T21:38:16.523 回答
1

你可以使用这样的东西

[(Student*)myStudentRepo.studentRepository[0] name];

或者您可以像这样覆盖 Student 的描述:在 Student.m 中添加:

-(NSString *)description{
        return [NSString stringWithFormat:@"Student Name:%@", self.name];
     }

每当您需要打印学生时,只需键入:

NSLog(%@, student);
于 2013-02-21T21:44:19.813 回答
1

如果您希望确保您的集合实际上只包含Student对象,相当于 Java 的参数集合,您可以这样做。有关字典的解决方案,请参阅此问题,数组解决方案将是类似的。您可以将该问题的公认解决方案与键入的 getter 和 setter 结合起来,以避免任何强制转换。

或者,如果您实际上并不关心确保只能Student添加​​对象,您可以编写一个扩展或类别来添加类型化的 getter 或 setter - 这只是调用标准 setter 或 getter 根据需要添加强制转换。您也会在上述问题的答案中看到这种方法。

(这里没有代码,因为你会在另一个问题中找到你需要的一切。)

于 2013-02-21T21:56:09.020 回答