2013-02-21 67 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根據需要增加一個轉換。您也會在上述問題的答案中看到這種方法。

(這裏沒有代碼,你會發現你的其他問題需要)