2013-02-21 2 views
0

내가 읽은 것 NSMutableArray는 개체를 추가합니다.NSMutableArray에서 객체 변수를 인쇄하는 방법은 무엇입니까?

개체를 Student으로 캐스팅하지 않고 주어진 위치에서 Student 개체 변수를 어떻게 인쇄 할 수 있습니까?

나는 ArrayList<Student> 같은 것을 찾고 있는데, 쉽게 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]); 
+0

감사합니다! – Mythul

답변

2

게시 한 코드는 그대로있는 것이 좋습니다. Objective-C/Cocoa와 Java의 형식화 된 콜렉션에는 동일한 기능이 없습니다. 결과를 캐스팅해야합니다.

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

+1 또는'[myStudentRepo.studentRepository [0] name]'으로 사용할 수 있습니다. 경고를 나타내서는 안됩니다. – iDev

+2

@ACB'id' 객체에'name'을 호출하면 끝납니다.컴파일러가 어딘가에서'name' 메소드를 본다면 행복 할 것입니다. – rmaddy

1

당신은에 description 또는 debugDescription을 무시할 수 당신 Student 클래스 :

하지만,

// 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 개체 만 포함합니다. 자바 매개 변수 컬렉션과 동등한 작업을 수행 할 수 있습니다. 사전에 대한 해결책은 this question을 참조하십시오. 배열 솔루션은 유사합니다. 허용 된 솔루션을 입력 된 getters & 설정 자와 결합하여 캐스트를 피할 수 있습니다.

Student 개체 만 추가 할 수 있다는 사실을 실제로 염려하지 않으면 입력 된 가져 오기 도구 또는 설정 도구를 추가하는 확장 또는 범주를 작성할 수 있습니다.이 도구는 표준 설정 도구 또는 getter를 호출하여 필요에 따라 캐스트를 추가합니다. 위의 질문에 대한 대답에서도이 접근 방식을 볼 수 있습니다.

(당신이 다른 문제의 필요를 찾을 수 있습니다 여기에 없음 코드입니다.) 모든 도움

관련 문제