comment créer chaîne de tableau
-
11-09-2019 - |
Question
Je vais avoir NSMutableArray qui contenant les informations d'étudiants, maintenant je veux juste extraire le nom des élèves et leur note moyenne seulement, donc ce que je l'ai fait
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]);
}
Je suis en mesure d'exécuter ce pour la première fois, mais quand je fais le scan automatique, je peux exe pour le 1er, 2ème, 3ème boucle, mais des applications puis mettre fin à show comme ci-dessous,
2009-12-02 14: 57: 37,908 AppBuzz [13073: 207] * Mettre fin à l'application du fait exception uncaught 'NSInvalidArgumentException', raison: « * - [NSCFArray insertObject: atIndex:]: tenter d'insérer nulle » 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 ) Mettre fin à appelé après avoir jeté une instance de « NSException » Programme signal reçu: « SIGABRT »
.comment cela peut être améliorer
Merci
La solution
Comprenez-vous les affirmations?
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];
}
}
...
Autres conseils
Comme il ressemble à des étudiants est une collection de cacao, vous pouvez utiliser les éléments suivants:
NSArray *studentNames = [students valueForKey:@"name"];
Voir la KVC Set et opérateurs multidisque pour plus d'informations.