2013-02-21 68 views
0

从我读的NSMutableArray添加对象。如何从NSMutableArray打印对象变量?

如何从给定位置打印Student对象变量而不将对象作为Student投射。

我在找Java like ArrayList<Student>这样的东西,所以我可以轻松打印ArrayList.get(i).getNameArrayList.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]); 
+0

谢谢大家的帮助! – Mythul 2013-02-21 21:40:31

回答

2

您发布的代码是罚款原样。 Objective-C/Cocoa在Java的类型化集合中没有等价物。你需要投射结果。

其实,有一个小窍门,你可以这样做:

NSLog(@"Value: %@", [myStudentRepo.studentRepository[0] valueForKey:@"name"]); 
+1

+1,或者它可以用作'[myStudentRepo.studentRepository [0]名称]'。它不应该显示任何警告。 – iDev 2013-02-21 22:00:36

+2

@ACB自从你最终在一个'id'对象上调用'name'以来就是真的。只要编译器从某个地方看到了'name'方法,它就会很开心。 – rmaddy 2013-02-21 22:40:19

1

你可以在覆盖descriptiondebugDescriptionStudent类:

由于我没有你的学生的弥补,请允许的直接的方式下面的例子:

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

这得到与大型和复杂的对象繁琐,虽然。

1

你可以使用这样的事情

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

或者你可以重写这样学生的描述:在Student.m 补充一点:

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

当你需要打印学生只需输入:

NSLog(%@, student); 
1

如果你想确保你的收藏真的y只包含Student对象,相当于Java的参数集合,您可以这样做。有关字典的解决方案,请参阅this question,阵列解决方案将类似。您可以将已接受的解决方案与该类型的获取者设置器相结合以避免任何投射。

另外,如果你没有真正关注过确保只有Student对象可以被添加,你可以写它增加了一个类型的getter或setter的延伸或类别 - 这只是调用标准setter或getter根据需要增加一个转换。您也会在上述问题的答案中看到这种方法。

(这里没有代码,你会发现你的其他问题需要)