Reputation: 1807
From what I've read NSMutableArray
adds objects.
How can I print the Student
object variables from a given position without casting the object as a Student
.
I'm looking for something like ArrayList<Student>
in Java so i can easily print 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]);
Upvotes: 0
Views: 2471
Reputation: 53000
If you wish to ensure your collection actually only contains Student
objects, the equivalent of Java's parametric collection you can do this. See this question for a solution for dictionaries, an array solution would be similar. You can combine the accepted solution to that question with typed getters & setters to avoid any casts.
Alternatively if you are not actually concerned over ensuring only Student
objects can be added you can write an extension or category which adds a typed getter or setter - this just calls the standard setter or getter adding an casts as needed. You'll see this approach in the answers to the above question as well.
(No code here as you'll find all you need in the other question.)
Upvotes: 1
Reputation: 7123
You Can use something like this
[(Student*)myStudentRepo.studentRepository[0] name];
Or you can override the description of the Student like this: in Student.m add this :
-(NSString *)description{
return [NSString stringWithFormat:@"Student Name:%@", self.name];
}
Whenever you need to print the Student just type:
NSLog(%@, student);
Upvotes: 1
Reputation: 4946
You could override description
or debugDescription
in you Student
class:
Since I don't the make up of your student, please allow the following example of a straight forward way:
// could also be -(NSString*)debugDescription
- (NSString *)description {
return [NSString stringWithFormat:@"Prop1: %@ \nIntVal1: %d\nfloatVal1 = %3.2f", self.prop1, self.intVal1, self.floatval1];
}
This gets tedious with large and complex objects, though.
Upvotes: 1
Reputation: 11436
You can use KVC (Key Value Coding) to access the properties of an object without casting it:
[[myStudentRepo.studentRepository objectAtIndex:0] valueForKey:@"name"];
Upvotes: 1
Reputation: 318814
The code you posted is fine as-is. There is no equivalent in Objective-C / Cocoa to Java's typed collections. You need to cast the results.
Actually, there is a little trick you can do:
NSLog(@"Value: %@", [myStudentRepo.studentRepository[0] valueForKey:@"name"]);
Upvotes: 2