Updating NSMutableArray of dictionary objects - iphone

I have a NSMutableArray (i.e. "stories") of dictionary items.
I can read the dictionary items in the array just fine, e.g.
[[[stories objectAtIndex: b] objectForKey: #"title"]
But, now I am trying to update (i.e. replace) a couple of objects e.g. "title" & "matchingword", but I cannot find the right code. Any suggestions are much appreciated.
I tried this, but it seems to be adding entirely new objects to the array
NSMutableDictionary *itemAtIndex = [[NSMutableDictionary alloc]init];
[itemAtIndex setObject:[[placesArray objectAtIndex:a]objectAtIndex:0] forKey:#"reference"];
[stories replaceObjectAtIndex:x withObject:itemAtIndex]; // replace "reference" with user's unique key
[itemAtIndex release];
I also tried this (but didn't work either):
//NSMutableDictionary *itemAtIndex2 = [[NSMutableDictionary alloc]init];
//[itemAtIndex2 setObject:[separatePlaces objectAtIndex:x] forKey:#"matchingword"];
//[stories insertObject:itemAtIndex2 atIndex:x]; // add the unique matching word to story
//[itemAtIndex2 release];
Help appreciated. Thanks.

You need to grab the dictionary you want to mod.
NSMutableDictionary *temp = [stories objectAtIndex: b];
The change the value:
[temp setObject:#"new Info" forKey:#"title"];

Related

how to add object at specified index in NSMutable array?

How can I add object at specified index?
in my problem
NSMutableArray *substring
contains index and object alternatively
and I need to add it to the another array str according to index I getting from this array.
NSMutableArray *str=[NSMutableArray new];
if ([substrings containsObject:#"Category-Sequence:"])
{
NSString *index=[substrings objectAtIndex:5];
//[substrings objectAtIndex:5]
gives me integer position at which I need to add object in `str` array,
gives 5,4,8,2,7,1 etc
NSString *object=[substrings objectAtIndex:1];
//[substrings objectAtIndex:1] gives object,gives NSString type of object
[str insertObject:object atIndex:(index.intValue)];
}
please suggest some way to achieve it.
Thanks in advance!
Allocate the array first & then try to add objects in it.
NSMutableArray *str = [[NSMutableArray alloc]init];
if ([substrings containsObject:#"Category-Sequence:"])
{
NSString *index=[substrings objectAtIndex:5];
NSString *object=[substrings objectAtIndex:1];
[str insertObject:object atIndex:(index.intValue)];
}
Allocate the NSMutableArray before inserting objects into it:
NSMutableArray *strMutableArray = [[NSMutableArray alloc] init];
(You’ll also need to release it when you’re done if you’re not using ARC.)
Or you could also use a temporary object, if you don’t need to keep strMutableArray:
NSMutableArray *strMutableArray = [NSMutableArray array];
Then you can insert objects into the NSMutableArray.
Be careful with using indexes of and in different arrays, however. There might be a better way to do what you want.

Sort an NSMutableArray / Dictionary with several objects

I am having a problem that I think I am overcomplicating.
I need to make either an NSMutableArray or NSMutableDictionary. I am going to be adding at least two objects like below:
NSMutableArray *results = [[NSMutableArray alloc] init];
[results addObject: [[NSMutableArray alloc] initWithObjects: [NSNumber numberWithInteger:myValue01], #"valueLabel01", nil]];
This gives me the array I need but after all the objects are added I need to be able to sort the array by the first column (the integers - myValues). I know how to sort when there is a key, but I am not sure how to add a key or if there is another way to sort the array.
I may be adding more objects to the array later on.
Quick reference to another great answer for this question:
How to sort NSMutableArray using sortedArrayUsingDescriptors?
NSSortDescriptors can be your best friend in these situations :)
What you have done here is create a list with two elements: [NSNumber numberWithInteger:myValue01] and #"valueLabel01". It seems to me that you wanted to keep records, each with a number and a string? You should first make a class that will contain the number and the string, and then think about sorting.
Doesn't the sortedArrayUsingComparator: method work for you? Something like:
- (NSArray *)sortedArray {
return [results sortedArrayUsingComparator:(NSComparator)^(id obj1, id obj2)
{
NSNumber *number1 = [obj1 objectAtIndex:0];
NSNumber *number2 = [obj2 objectAtIndex:0];
return [number1 compare:number2]; }];
}

iPhone Programming - complex JSON Parsing - UITableView

Hey guys :) I am quite new to stack overflow and iPhone programming. I am trying to parse a complex JSON to display some stuff in the UITableView.
a part of the JSON structure -
{"1":{"1":"Ent1","done":"No"},"2":{"1":"Ent2","done":"No"}}
I am able to parse through the main keys "1" and "2" and able to grab the values corresponding to the key "1" inside {"1":"Ent1","done":"No"}, {"1":"Ent2","done":"No"} store them into a dictionary/ a string with the following code :
for (NSString *key in dict)
{
NSString *answer = [dict objectForKey:#"1"];
NSLog(#"%#", answer);
}
The result is Ent1 and Ent2 because the code iterates over the for loop and checks for the objects with key "1".
The problem is this - I want to store both the values(Ent1 and Ent2) into an array.
I use the following code:
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects: answer, nil];
but it just takes the last index in the dictionary which is Ent2.
Could you please tell me how could I add both the values for key 1 into an array?
Thanks in advance :)
To add to jamapag's answer, you can also use JSON libraries in objective C which do all the work for you like SBJSON or YAJL, or even as part of the more recent versions of the mac/iOS SDKs, NSJSONSerialization.
NSMutableArray *array = [[NSMutableArray alloc] init];
for (NSString *key in dict)
{
NSString *answer = [dict objectForKey:key];
[array addObject:answer];
}

Creating a Two-Dimensional Array with Concrete Positions

I need to create a custom array:
In php I would define as follows:
$myarray[100][80] = 1;
But I don't know how to do it in objective-c...
I don't need an array [0][0],[0][1],[0][2], ... I only need concrete positions in this array [80][12], [147][444], [46][9823746],...
The content of these positions always will be = 1;
for this you would use a dictionary rather than an array as they are always 0,1,2 keyed so something along the lines of:
NSNumber *one = [NSNumber numberWithInt:1];
NSString *key = #"80,12";
NSDictionary *items = [NSDictionary dictionaryWithObject:one forKey:key];
Then to pull them out again you would use the objectForKey: method.
You cannot put ints directly into arrays or dictionaries that's why it is wrapped in the NSNumber object. To access the int after getting the NSNumber out of the dictionary you would use something like:
NSNumber tempNum = [items objectForKey:key];
int i = tempNum.intValue;
See the docs here for a full explanation of the NSDictionary class. Hope this helps...
I an not a PHP master but I believe in php arrays are not real arrays they are hash tables right?
Anyway, I think you are looking for NSDictionary or NSMutableDictionary class.
That looks more like a bitset than an array.
Allocating so many cells for that seems useless, so maybe you could revert the problem, and store the positions in an array.
Well in objective c we can use NSMutableArray to define 2-D arrays.
See the following code, it might help you
NSMutableArray *row = [[NSMutableArray alloc] initWithObjects:#"1", #"2", nil];
NSMutableArray *col = [[NSMutableArray alloc] init];
[col addObject:row];
NSString *obj = [[col objectAtIndex:0] objectAtIndex:0];
NSLog(#"%#", obj);

Creating Arrays from a plist file in iphone SDK 3.3 and up : objective c

I have run into this issue and have put some major time into finding the answer. I am somewhat new to objective c but not to programming.
Here is my question.
I have a plist file with this structure
root {
A (
{songTitle : contents of song},
{songTitle : contents of song}
),
B (
{songTitle : contents of song}
),
C (
{songTitle : contents of song}
),
... kepps going
}
Sorry if the the plist structure is not correct.
Pretty much I have a root dictionary (that is what it comes with) that contains an array of A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,...Z (alphabet)
Each letter of the alphabet array contains 1 or more dictionaries that have a key, value pair of songTitle (this could be any string) as the key and the song lyrics for the value.
My issue here is I need to create an array of all song titles and have been having a rough time trying to find out how to do this. I own 4 books on object c and none of them go into detail about multidimensional arrays and how to access pieces inside them.
I have created an array with all the letters and have created an array that contains the objects from each letter.
Like I stated before I need to find out how to make an array that contains each song title.
If you can help me that would save me a lot of time.
Thanks,
Wes
I am guessing you are suggesting I change my root from a dictionary to an array?
Maybe it might be better to show my code here.
Also I have attached an updated version of my plist file
Sorry seems I cannot add the image here but you can view it
http://www.wesduff.com/images/forum_images/plist_examp.png
So as you can see I have updated the plist file to show the array of letters that each contain multiple dictionaries. Each dictionary has a songTitle and a songLyrics.
How can I write code to get an array of songTitles.
Here is what I have come up with so far
NSString *path = [[NSBundle mainBundle] pathForResource:#"songs" ofType:#"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
//This gives me an array of all the letters in alphabetical order
NSArray *array = [[dict allKeys] sortedArrayUsingSelector:#selector(compare:)];
/**
Now I need to find out how to get an array of all songTitles
**/
I am still working on this and looking through what others have written but have not found anything yet.
As the first answer has suggested, should I change the root to an array or keep it as I have it in this plist image I have attached.
Thanks again,
Wes
Ok so I did some more digging and came up with this from the plist file that was included in this picture
http://www.wesduff.com/images/forum_images/plist_examp.png
- (void)viewDidLoad {
//path for plist file
NSString *path = [[NSBundle mainBundle] pathForResource:#"songList" ofType:#"plist"];
//dictionary created from plist file
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
//release the path because it is no longer needed
[path release];
//temp array to hold an array of all alphabetical letters
NSArray *array = [[dict allKeys] sortedArrayUsingSelector:#selector(compare:)];
//assign array to allLetters array
self.allLetters = array;
//Create two mutable arrays for the songArray (could do a little cleaner job of this here)
NSMutableArray *songArray = [[NSMutableArray alloc] init];
NSMutableArray *songTitles = [[NSMutableArray alloc] init];
//Add messy array to songArray then we can work with the songArray (maybe something better to do here)
for(id key in dict)
{
[songArray addObject:[dict objectForKey:key]];
}
//temp array to hold a messy array for all of the songTitles
NSArray *tempArray = [songArray valueForKey:#"songTitle"];
//go through the temparray and clean it up to make one array of all song titles and sort them
for (NSUInteger i = 0; i < [tempArray count]; i++) {
[songTitles addObjectsFromArray:[[tempArray objectAtIndex:i] sortedArrayUsingSelector:#selector(compare:)]];
}
//assign all song titles to our array of songTitles
self.allSongTitles = songTitles;
[dict release];
[allSongTitles release];
[songArray release];
[tempArray release];
[array release];
[super viewDidLoad];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
I am sure there is probably a better way to do this but this is what I have come up with on my own. Thanks
If you have single array with the contents of all the letters, the rest is fairly simple. Iterate through the objects and call the dictionary method allKeys on each one. Each call to allKeys will return an NSArray containing the keys of that specific dictionary, which you can then place into another array.
EDIT
I made a mistake, didn't go deep enough. This is what I would do:
NSString *path = [[NSBundle mainBundle] pathForResource:#"songs" ofType:#"plist"];
NSDictionary plistDict = [NSDictionary dictionaryWithContentsOfFile:path]; //not using alloc and init means this isn't retained, so it will be autoreleased at the end of the method
NSArray *allLetterContents = [plistDict allValues]; // array of arrays, where each element is the content of a 'letter' in your plist (i.e. each element is an array of dictionaries)
NSMutableArray *allSongTitles = [[[NSMutableArray alloc] init] autorelease];
for(NSArray *oneLetterContents in allLetterContents)
{
for(NSDictionary *song in oneLetterContents)
{
[allSongTitles addObject:[song objectForKey:#"songTitle"]]
}
}
return allSongTitles;
This array isn't guaranteed to be sorted alphabetically, so you'll have to call [sortedArrayUsingSelector:] on it.
Reference:
NSMutableArray Class Reference
NSDictionary Class Reference