简体   繁体   中英

Searching an Array of objects to return objects match a property value

I have an array of objects (240 objects) to be precise, all objects have a property called "round", i want to have a second array where i can store objects if round == x.

x is whatever number i decide.

-(void) parseXMLFixtures
{

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"somethinggoeshereiwthanapikey"]];

    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    NSString *xmlString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];

    NSDictionary *xml = [NSDictionary dictionaryWithXMLString:xmlString];

    NSMutableArray *items = [xml objectForKey:@"Match"];

    NSMutableArray *newFixtureObjectArray = [[NSMutableArray alloc] init];

    for (NSDictionary *dict in items) {
        FixturesObject *myFixtures = [FixturesObject fixtureFromXMLDictionary:dict];
        [newFixtureObjectArray addObject:myFixtures];
    }

    NSNull *nullValue = [NSNull null];

    [newFixtureObjectArray insertObject:nullValue atIndex:0];
    [newFixtureObjectArray insertObject:nullValue atIndex:1];

    [self setTableDataFixtures:newFixtureObjectArray];
}

Anyone knows how i could accomplish this?

//////

NSNumber *myRound = [NSNumber numberWithInt:11];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"round = %@", myRound];
NSArray *filteredArray = [_roundParser filteredArrayUsingPredicate:predicate];

NSLog(@" roundParser %@", filteredArray);



2014-02-13 01:00:18.383 [6864:70b]  roundParser (
)
2014-02-13 01:00:18.394 [6864:70b] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000101940795 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x00000001016a3991 objc_exception_throw + 43
    2   CoreFoundation                      0x00000001018f902f -[__NSArrayI objectAtIndex:] + 175
    3  Sagres Companion           0x0000000100019ddf -[FixturesController tableView:cellForRowAtIndexPath:] + 175

Try this,

int num = 11;
NSString *yourX = [NSString stringWithFormat:@"%d", num];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"round = %@", yourX];
NSArray *filteredArray = [objectArray filteredArrayUsingPredicate:predicate];

yourX is NSString of number that you need to find.

Use Predicate it will apply search for you array:

NSPredicate *sPredicate =
    [NSPredicate predicateWithFormat:@"SELF.round like '%@'",yourX];
[array filterUsingPredicate:sPredicate];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM