2

我有一个实体类数组(例如 SubmittedAnswer)。它的 JSON 格式如下所示。


{
"submittedAnswers": [{
    "submittedQuestionId": "C7B3C4BE-CC3C-438F-A118-E798884A5FE0",
    "serialNumber": 4,
    "option": " it has a very large mass.",
    "testQuestionId": "55230160-b905-47d5-a91c-e1dda6dd0634",
}, {
    "submittedQuestionId": "9A6E9EA8-1BC0-4ED9-81E8-28B7E554D5E0",
    "serialNumber": 1,
    "option": " downward",
    "testQuestionId": "fd0b3ae0-e999-48a6-89b8-a89b02e7b793",
}]

}

我想从“ submitQuestionId ”为“某事......”的那个数组中找到“ option ”字段。我不想使用 for 循环。目前我正在使用以下代码。

NSString *submittedQuestionId = "something...."
int index    = [[submittedAnswers valueForKey:@"submittedQuestionId"] indexOfObject:submittedQuestionId];
NSString *option = [[submittedAnswers valueForKey:@"option"] objectAtIndex:index];

我需要更好的解决方案来解决这个问题。

4

2 回答 2

3

假设这submittedAnswers是 NSDictionary 对象的 NSArray,我在这里找到了答案: Stack Overflow > iPhone - Searching NSArray of NSDictionary objects

// Array `submittedAnswers` of sample data
NSArray* submittedAnswers = @[
@{
@"submittedQuestionId" : @"C7B3C4BE-CC3C-438F-A118-E798884A5FE0" ,
@"serialNumber" : @4 ,
@"option" : @" it has a very large mass." ,
@"testQuestionId" : @"55230160-b905-47d5-a91c-e1dda6dd0634" } ,
@{
@"submittedQuestionId" : @"9A6E9EA8-1BC0-4ED9-81E8-28B7E554D5E0" ,
@"serialNumber" : @1 ,
@"option" : @" downward" ,
@"testQuestionId" : @"fd0b3ae0-e999-48a6-89b8-a89b02e7b793" } ] ;


NSString *submittedQuestionId = @"9A6E9EA8-1BC0-4ED9-81E8-28B7E554D5E0" ;
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"submittedQuestionId = %@", submittedQuestionId] ;
NSArray* foundQuestions = [submittedAnswers filteredArrayUsingPredicate:predicate] ;
NSDictionary* foundQuestion = foundQuestions[0] ;
于 2012-12-20T16:06:20.907 回答
2
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"submittedQuestionId == %@", yourSubmittedQuestionId];
NSArray *filteredArray = [myArray filteredArrayUsingPredicate:predicate];
id firstFoundObject = nil;
if ([filteredArray count] > 0) {
    firstFoundObject = [filteredArray objectAtIndex:0];
}

请确保您的SubmittedAnswer班级有财产submittedQuestionId

于 2012-12-20T16:10:56.847 回答