I have 5 animal objects and i trying to save it in a NSMutableDIctionary. However, according to my code below, only the last animal gets saved in the NSMutableDIctionary.
I don't think i am looping it correctly.
for(int i = 0; i < animalCount; i++) {
[allContacts setObject:name forKey:#"name"];
[allContacts setObject:age forKey:#"age"];
[allContacts setObject:gender forKey:#"gender"];
}
The output of the above displays as follows: (Only the last animal object gets displayed)
{
name = fish;
age = 6;
gender = "female";
}
How i want is that, all five animal objects to be saved in the NSMutableDIctionary so i can display them in a UITableView.
{
name = "cow";
age = 4;
gender = "male";
},
{
name = "dog";
age = 15;
gender = "male";
},
{
name = "fish";
age = 6;
gender = "female";
}
Key of NSMutableDictionary is unique.
What you want do is build an Array and every object of this Array is a Dictionary
NSMutableArray * contentsArray = [[NSMutableArray alloc] init];
for(int i = 0; i < animalCount; i++) {
NSMutableDictionary * allContacts = [[NSMutableDictionary alloc] init];
[allContacts setObject:name forKey:#"name"];
[allContacts setObject:age forKey:#"age"];
[allContacts setObject:gender forKey:#"gender"];
[contentsArray addObject:allContacts];
}
First create a NSMutableArray in order to loop and create the dictionaries. Then create individual dictionaries.
NSMutableArray *outputArray = [NSMutableArray array];
for ( int i=0; i< animalCount; i++) {
NSMutableDictionary *internalDictionary = [NSMutableDictionary dictionary];
[internalDictionary setObject:[nameArray objectAtIndex: i] forKey:#"name"];
[internalDictionary setObject:[ageArray objectAtIndex: i] forKey:#"age"];
[internalDictionary setObject:[genderArray objectAtIndex: i] forKey:#"gender"];
[outputArray addObject:internalDictionary];
}
NSLog(#"%#",outputArray);
Cheers!
You need an array of dictionaries, where your keys are constants (name, age, gender) and your values should be considered from their index (you'll need an array of names, ages, and genders), unless you'll have a lot of similar dictionaries:
NSMutableArray * contentsArray = [NSMutableArray new];
for(int i = 0; i < animalCount; i++) {
NSMutableDictionary * allContacts = [[NSMutableDictionary alloc] init];
[allContacts setObject:arrNames[i] forKey:#"name"];
[allContacts setObject:arrAges[i] forKey:#"age"];
[allContacts setObject:arrGenders[i] forKey:#"gender"];
[contentsArray addObject:allContacts];
}
or in modern objective c (simpler & shorter):
NSMutableArray *contentsArray = [NSMutableArray new];
for(int i = 0; i < animalCount; i++) {
[contentsArray addObject:#{#"name" : arrNames[i],
#"age" : arrAges[i],
#"gender" : arrGenders[i]}];
}
The reason is every time you are looping, you are updating the keys of your MSMutableDictionary, but you are not saving it anywhere.
Just take an NSMutableArray and save your dictionaries every time you update it.
So, first initialise the array outside the loop-
NSMutableArray *allContactsArray = [[NSMutableArray alloc] initWithCapacity: animalCount];
Now, run the loop, and save the dictionary every time before you loose it.
for(int i = 0; i < animalCount; i++) {
[allContacts setValue:name forKey:#"name"];
[allContacts setValue:age forKey:#"age"];
[allContacts setValue:gender forKey:#"gender"];
//save the allContacts dictionary in the array
[allContactsArray insertObject:allContacts atIndex:i];
}
This way you also you at what index you are saving your dictionary while adding.
I think you are mistaken. You should be saving dictionaries into an array, to populate tableview.
NSMutableArray *animals = [NSMutableArray array];
for(int i = 0; i < animalCount; i++) {
NSDictionary *dict = #{#"name" : name, #"age" : age, #"gender" : gender};
[animals addObject:dict];
}
Access in cellForRowAtIndexPath using:
NSDictionary *dict = animals[indexPath.row];
cell.textLabel.text = dict[#"name"];
Related
I'm having difficulty figuring out how to incorporate a counter so the "setObject" increments it's 'Save' in this for..loop.
NSMutableArray *NewArray = [NSMutableArray new];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for ( DBFILESMetadata *entry in result.entries) {
[dict setObject:entry.pathDisplay forKey:#"pathDisplay"];
[dict setObject:entry.name forKey:#"name"];
[NewArray addObject:dict];
}
I'm sure this is an easy answer,the last line is only saving the last item of result.entries. The NewArray has the correct count of items, but every item in the array is the last item of result.entries:
2017-04-13 16:47:58.876 Sites[11145:688352] NewArray (
{
name = 229;
pathDisplay = "/Sites/229";
},
{
name = 229;
pathDisplay = "/Sites/229";
}
).
I need to add a counter of some type to set the next object, just confused on where it should go.
Thanks in advance.
I figured this out:
for ( DBFILESMetadata *entry in result.entries) {
[imagePaths addObject:entry.pathDisplay];
[names addObject:entry.name];
}
for(int i=0; i<[result.entries count]; i++) {
dict = #{#"name": names[i], #"pathDisplay": imagePaths[i]};
[allObjects addObject:dict];
}
The dictionary item keys must be different. Otherwise, you see always last set item. Because the dictionary will overide when the save same key. So you can use just like below.
1.Solutions
NSMutableArray *NewArray = [NSMutableArray new];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
int i = 0;
for ( DBFILESMetadata *entry in result.entries) {
[dict setObject:entry.pathDisplay forKey:[NSString stringWithFormat:#"pathDisplay%d",i]];
[dict setObject:entry.name forKey:[NSString stringWithFormat:#"name%d",i]];
[NewArray addObject:dict];
i++;
}
2.Solution
Create a class that will hold the json property, just like a below.
HoldJsonDataClass.h
#interface HoldJsonDataClass : JsonData
#property (nonatomic,retain) NSString *name;
#property (nonatomic,retain) NSString * pathDisplay;
#end
HoldJsonDataClass.m
#implementation HoldJsonDataClass
#end
And than fill the class to the array. This solution is more clear.
for ( DBFILESMetadata *entry in result.entries) {
HoldJsonDataClass *holdJsonClass = [HoldJsonDataClass new];
holdJsonClass.name = entry.name;
holdJsonClass.pathDisplay = entry.pathDisplay;
[NewArray addObject:holdJsonClass];
}
I have 2 arrays. Array A arrayA[0] contains {a,b,c,d,e...} and Array B arrayB[0] contains {a,b,c...}. And both arrays are mutable and have many objects. In NSMutableDictionary for each element in Array A (taken as key) should store entire Array B.
For example:
(key value)Array A[0] have entire (object value)Array B(0...200)
(key value)Array A[1] have entire (object value)Array B(0...200)
(key value)Array A[2] have entire (object value)Array B(0...200)
My code:
for (int i=0; i<100; i++)
{
[someDictionary setObject:arrayB forKey:arrayA[i]];
}
this doesn't work and i tried this too :
[someDictionary initWithObjects:arrayB forKeys:arrayA[i]]
You should use NSString for storing key in key-value pair. So i would recommend
for (int i=0; i<100; i++) {
NSString *str=(NSString *)arrayA[i];
[someDictionary setObject:arrayB forKey:str];
}
Your code looks fine in principle. Obviously being fixed to 100 elements is not nice, so I'd write
for (id key in self.arrayA)
[someDictionary setObject:self.arrayB forKey:key];
Try this answer. I don't know brother whether I am understanding your question correctly or wrongly.
Try my code:
NSMutableArray *tempA=[NSMutableArray array];
NSMutableArray *tempB=[NSMutableArray array];
for (int a = 0; a < 100; a++)
{
[tempA addObject:[NSString stringWithFormat:#"%d",a]];
}
NSMutableArray *dataArray=[NSMutableArray array];
NSMutableDictionary *dict;
for (int i = 0; i < [tempA count]; i++)
{
for (int a = 0; a < 100; a++)
{
dict=[NSMutableDictionary dictionary];
NSString* localTemp=[NSString stringWithFormat:#"key-%#",[tempA objectAtIndex:i]];
[tempB addObject:[NSString stringWithFormat:#"%d",a]];
id object=[tempB objectAtIndex:a];
[dict setObject:object forKey:localTemp];
[dataArray addObject:dict];
}
}
NSLog(#"Dictionary is---->%#",dataArray);
NSArray *arrayA = [NSArray arrayWithObjects:#"1",#"2", nil];
NSArray *arrayB = [NSArray arrayWithObjects:#"3",#"4", nil];
NSMutableDictionary *temp = [[NSMutableDictionary alloc]init];
for(int i =0 ; i<[arrayA count];i++)
{
[temp setObject:arrayB forKey:[arrayA objectAtIndex:i]];
}
Hi I would like to know how to do when you click a button it will add a new object in the array and it will not affect the other objects like this:
here is my code:
x = x + 1;
dictData = [[NSMutableDictionary alloc] init];
for (int i = 0; i < x; i++) {
[dictData setObject:[menuData itemName] forKey:#"dishName"];
[dictData setObject:#"1" forKey:#"quantity"];
[dictData setObject:[menuData itemPrice] forKey:#"price"];
[arrMut addObject:dictData];
}
This is the current output
{
name = charles1;
},{
name = charles1;
}
This is the expected output
{
name = charles1;
},{
name = charles2;
}
because you are adding a same dictionary
change it to
for (int i = 0; i < x; i++) {
dictData = [[NSMutableDictionary alloc] init]; // move this line to inside of the loop
[dictData setObject:[menuData itemName] forKey:#"dishName"];
[dictData setObject:#"1" forKey:#"quantity"];
[dictData setObject:[menuData itemPrice] forKey:#"price"];
[arrMut addObject:dictData];
}
or
for (int i = 0; i < x; i++) {
[arrMut addObject:[#{#"dishName" : [menuData itemName],
#"quantity" : #"1",
#"price" : [menuData itemPrice],
} mutableCopy]];
}
The [menuData itemName] method seems to be returning the same object everytime.
You could insert menuData objects in an array and then access a menuData object on each iteration of the for loop.
NSMutableArray *arrMenuData = //This array should contain the menuData objects
for (int i = 0; i < x; i++) {
dictData = [[NSMutableDictionary alloc] init]; // move this line to inside of the loop
[dictData setObject:[[arrMenuData objectAtIndex:i] itemName] forKey:#"dishName"]; //A typecast to menuData type may be required, please test.
[dictData setObject:#"1" forKey:#"quantity"];
[dictData setObject:[[arrMenuData objectAtIndex:i] itemPrice] forKey:#"price"];
[arrMut addObject:dictData];
}
I would like to create an array for iOS platform like the PHP syntax below, many thanks ~~
$createArray = array ();
for ($i = 0; $i<10; $i++) {
$createArray[$i]['name'] = $name;
$createArray[$i]['age'] = $age;
}
Save your values in NSDictionary and add that dictionary into your array
NSMutableArray *theArray = [NSMutableArray array];
for (int indexValue = 0; indexValue<10; indexValue++) {
NSMutableDictionary *theDictionary = [[NSMutableDictionary alloc] init];
[theDictionary setObject:name forKey:#"name"];
[theDictionary setObject:age forKey:#"age"];
[theArray addObject:theDictionary]
}
While Retrieving time,
NSString *name = [[theArray objectAtIndex:indexValue] objectForKey:#"name"];
NSString *age = [[theArray objectAtIndex:indexValue] objectForKey:#"age"];
you might find it helpful:
array = [[NSMutableArray alloc] init];
for (int i = 0; i < 8; i++) {
NSMutableArray *subArray = [[NSMutableArray alloc] init];
for (int j = 0; j < 8; j++) {
[subArray addObject:[NSNumber numberWithInt:0]];
}
[array addObject:subArray];
[subArray release];
}
also check this question
Try this.
array = [[NSMutableArray alloc] init];
for (int i = 0; i < 10; i++) {
NSMutableArray *subArray = [[NSMutableArray alloc] init];
for (int j = 0; j < 2; j++) {
//Do your Stuff
// [subArray addObject:name];
// [subArray addObject:Age];
}
[array addObject:subArray];
}
OR
Why can't try with the NSDictionary
You can use this. But this is not better way in IOS.
NSMutableArray *array[20];
for (int i=0;i< 20; i++)
{
array[i] = [NSMutableArray array];
for (int j=0;j<3;j++)
{
NSMutableDictionary *theDictionary = [[NSMutableDictionary alloc] init];
[theDictionary setObject:name forKey:#"name"];
[theDictionary setObject:age forKey:#"age"];
[[array[i] addObject:theDictionary]
}
}
First you to have set An NSMutableDictionary on .h file
#interface MSRCommonLogic : NSObject
{
NSMutableDictionary *twoDimensionArray;
}
then have to use following functions in .m file
- (void)setValuesToArray :(int)rows cols:(int) col value:(id)value
{
if(!twoDimensionArray)
{
twoDimensionArray =[[NSMutableDictionary alloc]init];
}
NSString *strKey=[NSString stringWithFormat:#"%dVs%d",rows,col];
[twoDimensionArray setObject:value forKey:strKey];
}
- (id)getValueFromArray :(int)rows cols:(int) col
{
NSString *strKey=[NSString stringWithFormat:#"%dVs%d",rows,col];
return [twoDimensionArray valueForKey:strKey];
}
I have an NSArray some thing like in the following format.
The group array is :
(
"Q-1-A1",
"Q-1-A9",
"Q-2-A1",
"Q-2-A5",
"Q-3-A1",
"Q-3-A8",
"Q-4-A1",
"Q-4-A4",
"Q-10-A2",
"Q-8-A2",
"Q-9-A2",
"Q-7-A1",
"Q-5-A2"
)
Now what i have to do is group the array elements some thing like this.
1 = ( "Q-1-A1","Q-1-A9")
2 = ("Q-2-A1","Q-2-A5",) ...
10 =("Q-10-A2")
can any one please help me how can i achieve this.
Thanks in advance.
Try
NSArray *array = #[#"Q-1-A1",
#"Q-1-A9",
#"Q-2-A1",
#"Q-2-A5",
#"Q-3-A1",
#"Q-3-A8",
#"Q-4-A1",
#"Q-4-A4",
#"Q-10-A2",
#"Q-8-A2",
#"Q-9-A2",
#"Q-7-A1",
#"Q-5-A2"];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
for (NSString *string in array) {
NSArray *components = [string componentsSeparatedByString:#"-"];
NSString *key = components[1];
NSMutableArray *tempArray = dictionary[key];
if (!tempArray) {
tempArray = [NSMutableArray array];
}
[tempArray addObject:string];
dictionary[key] = tempArray;
}
Create an NSMutableDictionary, then iterate through your 'group array'.
For each NSString object:
get the NSArray of componentsSeparatedByString:#"-"
use the second component to create a key and retrieve the object for that key from your mutable dictionary. If its nil then set it to an empty NSMutableArray.
add the original NSString to the mutable array.
Try this
NSArray *arrData =[[NSArray alloc]initWithObjects:#"Q-1-A1",#"Q-1-A9",#"Q-2-A1",#"Q-2-A5",#"Q-3-A1",#"Q-3-A8",#"Q-4-A1",#"Q-4-A4",#"Q-10-A2",#"Q-8-A2",#"Q-9-A2",#"Q-7-A1",#"Q-5-A2", nil ];
NSMutableDictionary *dictList = [[NSMutableDictionary alloc]init];
for (int i=0; i<[arrData count];i++) {
NSArray *arrItem = [[arrData objectAtIndex:i] componentsSeparatedByString:#"-"];
NSMutableArray *arrSplitedItems = [dictList valueForKey:[arrItem objectAtIndex:1]];
if (!arrSplitedItems) {
arrSplitedItems = [NSMutableArray array];
}
[arrSplitedItems addObject:[arrData objectAtIndex:i]];
[dictList setValue:arrSplitedItems forKey:[arrItem objectAtIndex:1]];
}
NSArray *sortedKeys =[dictList allKeys];
NSArray *sortedArray = [sortedKeys sortedArrayUsingComparator:^(id str1, id str2) {
return [((NSString *)str1) compare:((NSString *)str2) options:NSNumericSearch];
}];
for (int i=0; i<[sortedArray count]; i++) {
NSLog(#"%#",[dictList objectForKey:[sortedArray objectAtIndex:i]]);
}
listOfYourMainArray/// Its YOur main Array;
temArray = (NSArray *)listOfYourMainArray; // Add Your main array to `temArray`.
NSMutableDictionary *lastDic = [[NSMutableDictionary alloc] init]; /// YOu need to creat Dictionary for arrange your values.
for (int i = 0; i< listOfYourMainArray.count; i++)
{
for (int j = 0 ; j < temArray.count; j ++)
{
if (([[temArray objectAtIndex:j] rangeOfString:[NSString stringWithFormat:#"Q-%d", i] options:NSCaseInsensitiveSearch].location != NSNotFound))
{
[lastDic setValue:[temArray objectAtIndex:j] forKey:[NSString stringWithFormat:#"%d", i]];
}
}
}
NSLog(#"%#", lastDic)