Use a for loop to set values in an array - ios

I have a UITableViewController that uses an array with values for every entry in the rows.
I want to set the values of that array by iterating over values read from a JSON file.
This is the new method I have created to read that data into an array and return it to my view controller. I don't know where to return the array, or how to really set it.
+(NSArray *)setDataToJson{
NSDictionary *infomation = [NSDictionary dictionaryWithContentsOfJSONString:#"Test.json"];
NSArray *test = [infomation valueForKey:#"Animals"];
for (int i = 0; i < test.count; i++) {
NSDictionary *info = [test objectAtIndex:i];
NSArray *array = [[NSArray alloc]initWithObjects:[Animal animalObj:[info valueForKey:#"AnimalName"]
location:[info valueForKey:#"ScientificName"] description:[info valueForKey:#"FirstDesc"] image:[UIImage imageNamed:#"cat.png"]], nil];
return array;
I know that my animalObj function worked when the data was local strings(#"Cat") and my dictionaryWithContentsOfJSONString works because I have tested, but I haven't used this function to set data to an array, only to UILabels, so this is where I am confused, on how to set this data into an array. But still use the For loop.

You want to use an instance of
NSMutableArray,
which will let you incrementally add elements to the array as you
iterate with the for-loop:
...
NSMutableArray *array = [NSMutableArray array];
for (int i = 0; i < test.count; i++) {
NSDictionary *info = [test objectAtIndex:i];
Animal *animal = [Animal animalObj:[info valueForKey:#"AnimalName"]
location:[info valueForKey:#"ScientificName"]
description:[info valueForKey:#"FirstDesc"]
image:[UIImage imageNamed:#"cat.png"]];
[array addObject:animal];
}
return array;
Because NSMutableArray is a subclass of NSArray, there's no need change the return type of your method.

Related

Compare the unique index value with another array in objective C

There is an array having same objects in single array , i need to compare these array’s index with another array.. Give me a help.
Something like:
NSMutableArray *latArray =
[NSMutableArray arrayWithObjects:#“43.20,#“43.23”,#“43.24”,#“43.20”,nil];
NSMutableArray *lngArray =
[NSMutableArray arrayWithObjects:#“76.90”,#“76.94”,#“76.92”,#“76.90”,nil];
NSMutableArray *imagesArray =
[[NSMutableArray alloc] initWithObjects:#"1.jpg", #"2.jpg”,#“3.jpg”,#“4.jpg”,nil];
resultResult = #"1.jpg", #“4.jpg” // because the index 0 and index 3 same values in both array.
I would wrap your coordinates into location objects and use them as the keys in a dictionary. This would allow to check for duplicate coordinates, like this:
NSMutableDictionary *results = [[NSMutableDictionary alloc] init];
for (int i = 0; i < [imagesArray count]; i++)
{
// Wrap coordinates into a NSValue object
// (CLLocationCoordinate2D is a C-struct that cannot be used as a dictionary key)
// (CLLocation also does not implement required methods to be usable as a dictionary key)
NSValue *loc = [NSValue valueWithMKCoordinate:CLLocationCoordinate2DMake(
((NSNumber)[latArray objectAtIndex:i]).doubleValue,
((double)[lngArray objectAtIndex:i]).doubleValue)];
// 1. If you only want the first occurrence of a specific location, use this:
if ([results objectForKey:loc] == nil)
{
[results setObject:[imagesArray objectAtIndex:i] forKey:loc];
}
// 2. Or, if you want the last occurrence of a specific location, use this:
[results setObject:[imagesArray objectAtIndex:i] forKey:loc];
}
I think you are trying the check for the same objects in an array. If so do the following.
for(int i=0;i<yourarray.count;i++)
{
NSString *yourstring=[yourarray objectatindex:i];
for(int k=0;k<yourarray.count;k++)
{
if(i!=k)
{
NSString *yourstring2=[yourarray objectatindex:k];
if([yourstring isEqualtostring yourstring2])
{
//now you got equal objects. do what ever you want here
}
}
}
}

Looping thru NSArray of NSString logic

I need help with the following:
I have an NSArray with NSStrings, I want to loop thru these strings and find a matching string, when match is found the strings after this match will be extracted into an NSDictionary until a certain other match is hit.
Here is an example:
NSArray *array = #[#"Fruit",#"Apple",#"Vegtable",#"Tomato",#"Fruit",#"Banana",#"Vegtable",#"Cucumber"];
So I want to loop thru this array and split it in 2 arrays one for fruit and one for vegetable.
Anyone can help with the logic?
Thanks
This is probably the simplest way to solve the problem:
NSArray *array = #[#"Chair",#"Fruit",#"Apple",#"Orange",#"Vegetable",#"Tomato",#"Fruit",#"Banana",#"Vegetable",#"Cucumber"];
NSMutableArray *fruitArray = [NSMutableArray array];
NSMutableArray *vegetableArray = [NSMutableArray array];
NSMutableArray *currentTarget = nil;
for (NSString *item in array)
{
if ([item isEqualToString: #"Fruit"])
{
currentTarget = fruitArray;
}
else if ([item isEqualToString: #"Vegetable"])
{
currentTarget = vegetableArray;
}
else
{
[currentTarget addObject: item];
}
}
In one iteration over the array, you just keep adding items to a result array using a pointer to one of two result arrays according to the last occurrence of the #"Fruit" or #"Vegetable" string.
This algorithm ignores all items before the first occurrence of the #"Fruit" or #"Vegetable" string, because the currentTarget is initialized to nil, which ignores the addObject: messages. If you want different behaviour, just change the initialization.
You said you wanted the results in a NSDictionary, but didn't specify what should be the key. If you want one NSDictionary with two keys, Fruit and Vegetable, and values NSArrays containing the items, just use the arrays previously created:
NSDictionary *dict = #{ #"Fruit": fruitArray, #"Vegetable": vegetableArray };
PS: You have a typo in your example, Vegtable instead of Vegetable. I corrected it in my code, so keep it in mind.
If I completely understand you:
NSArray *array = #[#"Fruit",#"Apple",#"Vegtable",#"Tomato",#"Fruit",#"Banana",#"Vegtable",#"Cucumber"];
NSMutableArray *fruits = [NSMutableArray array];
NSMutableArray *vegtables = [NSMutableArray array];
for (NSInteger i = 0; i < array.count; ++i){
if ([array[i] isEqualToString:#"Fruit"]){
++i;
[fruits addObject:array[i]];
}
else if ([array[i] isEqualToString:#"Vegtable"]){
++i;
[vegtables addObject:array[i]];
}
}

How can I add elements to an NSDictionary in the following format?

I have an NSArray of names and ages. Now I am trying to create a new NSDictionary with item 0 holding the first name and first age and item 1 holding the second name and second age from the corresponding NSArray? Is that possible?
In my viewDidLoad:
NSMutableArray *Names = [[NSMutableArray alloc] init];
NSMutableArray *ages = [[NSMutableArray alloc] init];
for(int i = 0; i < 4; i++) {
[Names addObject:[candidates objectAtIndex:i]];
[ages addObject:[studenAge objectAtIndex:i]];
}
But how can I make an NSDictionary from this by order?
Final result
I want to write this NSDictionary into a .plist so it look like this:
Details
{
item 0
{
name:rahul
age:25
}
item 1
{
name:ram
age:26
}
item 2
{
name:aajy
age:20
}
item 4
{
name:raj
age:25
}
}
Dictionaries do not have an order.
Probably you want to add dictionaries to the array:
NSMutableArray *persons=[[NSMutableArray alloc]init];
for(int i=0;i<4;i++)
{
[persons addObject:# { #"name" : candidate[i], #"age" : studenAge[i] }];
}
You can sort this array with the sort-Methods of NSArray, NSMutableArray.
As mentioned by #Amin, dictionaries don't maintain order and since you seem to want an indexed access here is what I suggest as the final structure: an array of dictionaries:
NSMutableArray *details = [NSMutableArray array];
for (int i=0; i<4; i++) {
[details addObject:#{#"name": canditate[i], #"age":studentAge[i]}];
}
This will give you the following structure:
[{name:rahul, age:25}, {name:ram age:26},...]

NSMutableArray with NSDictionary to NSMutableDictionary

Here is the situation:
I have a request on AFNetworking that retrieves me a JSON with an NSArray.
My goal is to mutate the NSDictionaries inside it. I already made a mutableCopy of the array, but I want to know if I can easily mutate all the content. Will I have to iterate through the array manually?
NSJSONSerialization has options to allow you to control the mutability of the resulting data structure. Just pass the appropriate ones (probably NSJSONReadingMutableContainers) and there you go.
You cannot mutate NSDictionary, just because only NSMutableDictionary has method setObject:forKey:
So you should create mutableCopy of each dictionary and empty mutable array. Then with a forloop fill that array. Your code should be so:
- (NSMutableArray *)mutatedArrayFromArray:(NSArray *)array
{
NSMutableArray *resultArray = [NSMutableArray new];
if([array count] > 0)
{
for(int i = 0; i < count; i++)
{
NSMutableDictionary *mutatedItem = [[array objectAtIndex:i] mutableCopy];
[resultArray addObject:mutatedItem];
[mutatedItem release]; // only with ARC disabled
}
}
return [result autorelease]; // if ARC enabled : return result;
}

NSMutableDictionary -- using allKeysforObject not retrieving array values

NSMutableDictionary *expense_ArrContents = [[NSMutableDictionary alloc]init];
for (int i = 1; i<=4; i++) {
NSMutableArray *current_row = [NSMutableArray arrayWithObjects:#"payer_id",#"Expense_Type_id",#"Category_Id",#"SubCategory_Id",nil];
[expense_ArrContents setObject:current_row forKey: [NSNumber numberWithInt:i]];
}
NSArray *newArray = [expense_ArrContents allKeysForObject:#"payer_id"];
NSLog(#"%#",[newArray description]);
i want to get the list of key values containing the particular object which is in the array of values stored in nsmutabledictionary for a particular key.
In the line where you get all the keys ([expense_ArrContents allKeysForObject:#"payer_id"];) you actually get keys for an object that is not in any of the array's items. This #"player_id" is different object than the #"player_id" you added in current_row. In fact, maybe all of your rows have different #"player_id" objects (except if the compiler has made some optimization - maybe it threats that same string literal as one object instead of creating new object for each iteration).
Try creating an NSString object for the #"player_id" which you add to the current_row and then get all the keys for that same object:
NSString* playerId = #"player_id";
for(){
NSMutableArray *current_row = [NSMutableArray arrayWithObjects: playerId,...];
...
}
NSArray *newArray = [expense_ArrContents allKeysForObject:playerId];
Your NSArray *newArray = [expense_ArrContents allKeysForObject:#"payer_id"]; will not return any value because in expense_ArrContents there is no such key(#"payer_id"), instead there are keys like 1,2,3 etc.What is your requirement?Want to see what all keys are there in expense_ArrContents just log
NSArray*keys=[expense_ArrContents allKeys];
Try this :
NSMutableArray *array_key=[[NSMutableArray alloc]init];
for (NSString *key in expense_ArrContents) {
if ([[expense_ArrContents objectForKey:key] containsObject:#"payer_id"]) {
[array_key addObject:key];
}
}

Resources