0

私が読んだことから、NSMutableArrayオブジェクトが追加されます。

Studentオブジェクトを としてキャストせずに、特定の位置からオブジェクト変数を出力するにはどうすればよいですかStudent

Javaのようなものを探しているので、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]);
4

5 に答える 5

2

投稿したコードはそのままで問題ありません。Objective-C / Cocoa には、Java の型付きコレクションに相当するものはありません。結果をキャストする必要があります。

実際には、あなたができるちょっとしたトリックがあります:

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

あなたはクラスでオーバーライドすることができますdescriptiondebugDescriptionStudent

私はあなたの学生の構成員ではないので、次の簡単な方法の例を許可してください。

// 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、Java のパラメトリック コレクションに相当する方法でこれを行うことができます。辞書の解決策については、この質問を参照してください。配列の解決策も同様です。その質問に対する受け入れられた解決策を型指定されたゲッターとセッターと組み合わせて、キャストを回避できます。

Studentまたは、オブジェクトのみを追加できるようにすることを実際に気にしない場合は、型指定されたゲッターまたはセッターを追加する拡張機能またはカテゴリを作成できます。これは、必要に応じてキャストを追加する標準のセッターまたはゲッターを呼び出すだけです。このアプローチは、上記の質問に対する回答にも見られます。

(他の質問で必要なものがすべて見つかるので、ここにはコードはありません。)

于 2013-02-21T21:56:09.020 に答える
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

KVC (Key Value Coding) を使用して、キャストせずにオブジェクトのプロパティにアクセスできます。

[[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 に答える