Ed Bogaert
Ed Bogaert

Reputation: 1

NSArray extract items

I extract data from a NSMutableArray using NSPredicate:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", value];
NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate];

When I use:

NSLog(@"%@", results);

I get:

({pub_id = 102 "pub_name" = "some publisher" city = "Peshawar"});

I would like to extract values of all 3 items pub_id, pub_name, city.

Upvotes: 0

Views: 250

Answers (4)

TeaPow
TeaPow

Reputation: 677

What's being returned is an array containing 1 object (which denoted by the curly braces {} means a dictionary). To extract each of the three components, you can do:

NSString *pub_id = [[results objectAtIndex:0] valueForKey:@"pub_id"];
NSString *pub_name = [[results objectAtIndex:0] valueForKey:@"pub_name"];
NSString *city = [[results objectAtIndex:0] valueForKey:@"city"];

Bear in mind that this solution is only suitable for the example you've provided. If the query ever returns more than 1 object in the array, you'll need to use enumeration/for loop to read the results.

Upvotes: 1

user529758
user529758

Reputation:

The object you get out of the array using the prodicate is apparently an NSDictionary. Use the following code:

NSString *city = [[results objectAtIndex:0] valueForKey:@"city"];

et cetera.

Upvotes: 0

Kirby Todd
Kirby Todd

Reputation: 11556

To get all the values from a dictionary into an array do:

[dictionary allValues];

Upvotes: 0

Juan M.
Juan M.

Reputation: 146

I have understood that you want to get those three objects separately, isn't it? In case I am right:

NSLog(@"PUBID: %d \n PUBNAME: %@ \n CITY: %@", [[results objectAtIndex:0] intValue], [results objectAtIndex:1], [results objectAtIndex:2]);

This code should print
PUBID: 102 PUBNAME: some publisher CITY: Peshawar.

So your result from

[array_to_search filteredArrayUsingPredicate:predicate];

is another array and you can use that with objectAtIndex:

Upvotes: 0

Related Questions