0

私は学生の情報を含む NSMutableArray を持っています。今は学生の名前とその平均点のみを抽出したいので、私がしたこと

    NSMutableArray *stuCollection = [[NSMutableArray alloc] initWithCapacity:[students count]];

for (int i = 0; i < [students count]; i++) 
{
    if([students objectAtIndex:i] != NULL)
    {

    NSDictionary *dic = [students objectAtIndex:i];
    NSString *temp = [dic objectForKey:@"name"];

    [stuCollection  addObject:name];

    }   
}


for(int j=0; j< [stuCollection count]; j++)
{
    NSLOG(@"Name %@",[stuCollection objectAtIndex:j]);
}

これを初めて実行できますが、自動スキャンを行うと、1回目、2回目、3回目のループを実行できますが、次のようにアプリが終了します。

2009-12-02 14:57:37.908 AppBuzz[13073:207] * キャッチされていない例外 'NSInvalidArgumentException' が原因でアプリを終了しています。理由: '* -[NSCFArray insertObject:atIndex:]: nil を挿入しようとしています' 2009-12-02 14:57:37.916 AppBuzz[13073:207] Stack: ( 820145437, 837578260, 819694387, 819694291, 814683071, 814716415, 814716245, 17529, 24097, 814480795, 819893443, 819891231, 858682228, 861592624, 861585968, 8997, 8860 ) terminate called 「NSException」のインスタンスをスローした後、プログラムはシグナル「SIGABRT」を受け取りました。

これをどのように改善できるか

ありがとう

4

2 に答える 2

1

アサーションを理解していますか?

assert(students);
assert([students count]);

NSMutableArray * stuCollection = [[NSMutableArray alloc] initWithCapacity:[students count]];
assert(stuCollection);

for (int i = 0; i < [students count]; i++) {
    if ([students objectAtIndex:i] != NULL) {

        NSDictionary * dic = [students objectAtIndex:i];
        assert(dic);

        NSString * temp = [dic objectForKey:@"name"];
        assert(temp);

        assert(name);

        [stuCollection addObject:name];
    }
}
...
于 2009-12-02T07:39:17.207 に答える
0

学生はCocoaコレクションのように見えるので、次を使用できます。

NSArray *studentNames = [students valueForKey:@"name"];

詳細については、KVCセットおよび配列演算子を参照してください。

于 2009-12-02T07:17:26.953 に答える