I m doing stuff in which i need sorting as per category.
I have array of objects having objects as
array1 = name,roll number,group name.
array2 = name,roll number,group name.
I want to categorized above array based on same group. I don t want to compare with hard coded group name.
It means i want members with same country name in separate array. Here array count will not be hardcoded. It will create as data is present. My data is as below.
Please suggest me any logic.
Thanks...
Item 0
Student Name ="ABC"; Roll No ="12"; Country ="USA"
Item 1
Student Name ="DEF"; Roll No ="12"; Country ="INDIA"
Item 2
Student Name ="DEF"; Roll No ="12"; Country ="INDIA"
Item 3
Student Name ="DEF"; Roll No ="12"; Country ="USA"
How about just creating a simple class with properties containing these attributes?
Assuming you have a NSArray containing other NSArrays, filled with NSString objects (as your edit suggets), why not writing a simple method ?
Here is an example of method for an object having a property called myItems of type NSArray
// NSArray *myItems, containing your stuff
-(NSArray *)itemsWithCountryName:(NSString *)aCountryName {
NSMutableArray *items = [NSMutableArray arrayWithCapacity:[myItems count]];
NSArray *myItemAsAnArray;
for(myItemAsAnArray in [self myItems]) {
// your edit suggets 2 as the index for the country name
// maybe you can provide a defined constant
if([[myItemAsAnArray objectAtIndex:2] isEqualToString:aCountryName]) {
[items addObject:myItemAsAnArray];
}
}
return items;
}
But maybe you work with dictionaries...
-(NSArray *)itemsWithCountryName:(NSString *)aCountryName {
NSMutableArray *items = [NSMutableArray arrayWithCapacity:[myItems count]];
NSDictionary *myItemAsAnDictionary;
for(myItemAsAnDictionary in [self myItems]) {
// same again for the key
if([[myItemAsAnArray objectForKey:#"Country"] isEqualToString:aCountryName]) {
[items addObject:myItemAsAnArray];
}
}
return items;
}
Good luck !
Related
I'm using the value of two sliders as the first search criteria.
Now I want a second criteria. I have a
NSMutableArray *suitsArray;
which is containing up to 10 words, or it could be empty (0 words). Example of array:
2012-08-12 03:13:14.825 App[4595:f803] The content of array is(
mushroom,
grill,
pizza
)
What I want is this:
If suitsArray is like above, containing words mushroom, grill and pizza
and the "Suits" value in a dictionary is: "This wine suits mushroom dishes, grilled food, pizza and chicken."
This dictionary is added to searchResultsArray, same with all other dictionaries where "Suits" value containing words mushroom, grill and pizza.
But if suitsArray is empty of objects, skip this critera.
But I'm not sure how to write the code for it. Can you help me on it?
-(IBAction)searchButtonPressed:(id)sender{
resultObjectsArray = [NSMutableArray array];
for(NSDictionary *object in allObjectsArray)
{
NSString *objectPrice = [object objectForKey:#"75 cl price"];
NSString *suitsString = // the words in suitsArray
NSString *objectSuits = [object objectForKey:#"Suits"];
BOOL priceConditionGood = YES;
if (minPrisSlider.value <= maxPrisSlider.value && (winePrice.floatValue < minPrisSlider.value || winePrice.floatValue > maxPrisSlider.value))
priceConditionGood = NO;
if (priceConditionGood)
[resultObjectsArray addObject:object];
}
ResultsTableViewController *nextController = [[self storyboard] instantiateViewControllerWithIdentifier:#"ResultsController"];
nextController.objectsArray = [[NSMutableArray alloc]initWithArray:resultObjectsArray];
[self.navigationController pushViewController:nextController animated:YES];
}
It would be better to see if suitsArray contains the string objectSuits, rather than using rangeOfString.
if ([suitsArray containsObject:objectSuits]);
[resultObjectsArray addObject:object];
After edit: I think I understand now. This method looks at each word in suitsArray, and if it finds any of them in objectSuits, then object is added to the resultObjectArray.
for (NSString *aWord in suitsArray) {
if ([objectSuits rangeOfString:aWord].length == aWord.length) {
[resultObjectArray addObject:objectSuits];
break;
}
}
Second Edit: After further thought, the above code has a flaw in the logic that may or may not be important -- because it uses rangeOfString it will find words inside other words. So, if objectSuits was "This wine goes well with cheesecake" and suitsArray contained the word cheese, it would find a match (I can't imagine a wine that would be good with cheese would be good with cheesecake). So, here is a better solution, I think, that breaks objectSuit up into individual words and puts them into a set. suitsArray is also converted to a set, so that we can use intersectsSet: to find if there are any common words.
NSCharacterSet *sepSet = [NSCharacterSet characterSetWithCharactersInString:#" ,.;"];
NSArray *words = [objectSuits componentsSeparatedByCharactersInSet:sepSet];
NSSet *objectSuitsWords = [NSSet setWithArray:words];
NSSet *suitsSet = [NSSet setWithArray:suitsArray];
BOOL ans = [suitsSet intersectsSet:objectSuitsWords];
So, if ans is 1, then that object should be added to the results array. Notice that sepSet starts with a space and includes a comma, period, and semicolon. There might be other things you might want to include, but I think this should work in most cases.
I'm sorry for this (probably very) noob question, but i've been asked about this and can't see what's wrong (i'm java tought..)
This is what I have, data is loaded via JSON:
NSDictionary *myvalues = [myres objectForKey:#"0"];
this is the content if I output via NSLog:
({id = "1a";myval = 5;},
{id = "2b";myval="24.6";})
how do I iterate through myvalues and how do I get the values id and myval? Something like this i'm getting stuck:
for (NSArray* myvals_array in myvalues)
First it looks like the returned value is an Array, the content inside of the parentheses() denotes this. So I would try and set it as such instead of a Dictionary. Then you can enumerate through the array of dictionary's and get each dictionary inside:
for (id object in myvalues) {
NSDictionary *currentObject = (NSDictionary*)object;
NSString *myID = [currentObject valueForKey:#"id"];
NSString *myValue = [currentObject valueForKey:#"myval"];
NSLog(#"ID:%# VALUE:%#",myID,myValue);
}
This will enumerate through the array and create a dictionary for each entry, then get the values for each of the two elements inside. I just NSLog() them here but you can do whatever you want with the values.
I am building an app that uses a UPC data base API. I am getting back a JSON object, example from here: http://www.simpleupc.com/api/methods/FetchNutritionFactsByUPC.php
{
"success":true,
"usedExternal":false,
"result"
{
"calories_per_serving":"150",
"cholesterol_per_serving":"15",
"cholesterol_uom":"Mg",
"dvp_calcium":"30",
"dvp_cholesterol":"4",
"dvp_iron":"2",
"dvp_protein":"17",
"dvp_saturated_fat":"8",
"dvp_sodium":"10",
"dvp_total_fat":"4",
"dvp_vitamin_a":"10","
"dvp_vitamin_c":"0",
"dvp_vitamin_d":"25",
"fat_calories_per_serving":"25",
"fiber_per_serving":"<1",
"fiber_uom":"G",
"ingredients":"Fat Free Milk, Milk, Sugar, Cocoa (Processed With Alkali),
Salt, Carrageenan, Vanillin (Artificial Flavor),
Lactase Enzyme, Vitamin A Palmitate And Vitamin D3.",
"protein_per_serving":"8",
"protein_uom":"G",
"size":"240",
"units":"mL",
"servings_per_container":"8",
"sodium_per_serving":"230",
"sodium_uom":"Mg",
"total_fat_per_serving":"2.5",
"total_fat_uom":"G",
"trans_fat_per_serving":"0",
"trans_fat_uom":"G",
"upc":"041383096013"
}
}
My problem is with parsing the "ingredients" element, which is a sub list of the object dictionary.
How would you suggest parsing the ingredients list? If I could get it to an NSArray, assuming commas are separators, that would have been great.
I tried to do this, but looks like its just a string, so no way to parse it.
Any suggestion would be more than welcome. Thanks!
//Thats the whole JSON object
NSDictionary *json_dict = [theResponseString JSONValue];
//Getting "results" which has all the product info
NSArray *myArray = [[NSArray alloc] init];
myArray = [json_dict valueForKey:#"result"];
Now how do I get "ingredients" from myArray in an array form?
You're getting result as an array, but (in JSON terminology) it's not an array. It's an object, so use an NSDictionary. Something like this:1
NSDictionary *result = [json_dict objectForKey:#"result"];
Then you can get the inner ingredients object from that:
NSString *ingredients = [result objectForKey:#"ingredients"];
Edited as per #Bavarious' comment.
1Apologies for glaring errors, as I'm not terribly well-versed in Objective-C. You might need to allocate memory for the returned NSDictionary and NSString pointers; I'm not sure.
Here's all you need to do:
NSDictionary *json_dict = [theResponseString JSONValue];
// Use a key path to access the nested element.
NSArray *myArray = [json_dict valueForKeyPath:#"result.ingredients"];
EDIT
Whoops, Matt's right. Here's how to deal with the string value:
// Use a key path to access the nested element.
NSString *s = [json_dict valueForKeyPath:#"result.ingredients"];
NSArray *ingredients = [s componentsSeparatedByString:#", "];
Note that you might need to trim the '.' character off the last element of the array.
hy everyone,
i really need a helping hand here.
here is my problem:
i have an array with objects which each has two attributes:
1 is an NSSTring name
2 is an NSSNumber price
now i want to run through the array and add all the values to a new string:
the problem is i need the following output.
name (from object 1) : price (from object 1) then new line (\n)
name (from object 2) : price (from object 2) then new line (\n) ... and so on...
would be great if someone could help me here.
with kind regards, thomas
Try this:
// This contains your objects with names and prices;
NSArray *productArray;
...
// |listOfProducts| will be your string with all names and prices.
NSMutableString *listOfProducts = [[NSMutableString alloc] init];
// Build the list of products
for (Product *product in productArray) {
[listOfProducts appendFormat:#"%#: $%0.2f\n", product.name, product.price];
}
I need to select stories from a NSArray of XML by matching a string from an XML element against a list of strings in another NSArray
The XML contains stories, each story has three criteria, say 'Fruit', 'Veg', 'Spice', each containing a single phrase. A sample story might look like:
<story>
<title>I love cooking</title>
<fruit>Oranges</fruit>
<veg>Cauliflower</veg>
<spice>Mixed spice</spice>
<blurb>losts of text and stuff....</blurb>
</story>
I have three dictionaries of key/value pairs in a NSMutableDictionary generated from a pList
<Fruit:dictionary>
'Ripe bananas' : 1
'Green bananas' : 0
<Veg:dictionary>
'Green beans' : 1
'Cauliflower' : 0
<Spice:dictionary>
'Nutmeg' : 1
'Mixed spice' : 0
I don't know what the keys will be, and I need to match the tag in the story against the keys.
i.e. story fruit tag:'Ripe bananas' MATCHES 'Ripe bananas' in list of fruit keys
I can build three arrays of the keys using
NSMutableDictionary *fruitTagsDict = [prefsDictionary objectForKey:#"Fruits"];
NSArray *fruitTags = [fruitTagsDict allKeys];
I loop through the story XML extracting a tag
for (id myArrayElement in storyArray) {
NSString *fruitString = [NSString stringWithString:[myArrayElement fruit]];
//BOOL isTheObjectThere = [issueTags containsObject:fruitString];
NSString *vegString = [NSString stringWithString:[myArrayElement veg]];
NSString *spiceString = [NSString stringWithString:[myArrayElement spice]];
//if ([[fruitTags objectAtIndex:row] isEqualToString:fruitString]) {
//NSLog(#"Yo %#", fruitString);
// ADD TO A NEW ARRAY OF MATCHING STORIES
//}
// Fails because row is undeclared
}
Then I start to glaze out.
The isTheObjectThere line produces nil then crashes at end of loop
I've looked at:
Filter entire NSDictionaries out of NSArray based on multiple keys
Making the Code check to see if the Text in a Text box matches any of the Strings in an NSArray
It seems predicate is the answer but frankly I getting confused.
What I need to do in metacode
repeat with stories
if storyFruitTag is in fruitTagArray
OR storyVegTag is in vegTagArray
OR storySpiceTag is in spiceTagArray
Add to new array of matching stories
Hopefully I've explained enough to get some pointers, I looked into NSMutableSet and Intersect (Xcode: Compare two NSMutableArrays) but the power of too much information got to me
Here's a simple way to determine whether there are matches using key paths:
if ([prefsDict valueForKeyPath:[NSString stringWithFormat:#"Fruit.%#", storyFruitTag]] ||
[prefsDict valueForKeyPath:[NSString stringWithFormat:#"Veg.%#", storyVegTag]] ||
[prefsDict valueForKeyPath:[NSString stringWithFormat:#"Spice.%#", storySpiceTag]]) {
// one of the story's tags matches a key in one of the corresponding dictionaries
}