Pick out certain part of NSMutableAray - iphone

How would I pick out certain part of NSMutableArray?
One fielding array from server is 2012-09-01 09:00:00 America/Los_Angeles
I am trying to get just the time.
I was thinking turning it into a string and then getting it and then back into NSMutablearray to populate to tableview cells.
I am still looking at documentation
Options I am thinking of:
-subarrayWithRange:
componentsSeparatedByString:
UPDATE:
Here is what I am doing now to get the field of appointments
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
NSDictionary* myslots =[json objectForKey:#"slots"];
self.timesArray = [[NSMutableArray alloc] init];
NSLog(#"allslots: %#", myslots);
for (NSString *slotKey in myslots.allKeys) {
NSDictionary *slot = [myslots valueForKey:slotKey];
for (myDays in slot){
if ([[self.myDays objectForKey:#"isReservable"] isEqualToNumber:[NSNumber numberWithInt:1]])
[self.timesArray addObject:[self.myDays objectForKey:#"begin"]];
//NSLog(#"This is the times count: %#", timesArray.count);
}
}
NSLog(#"These are the times avail: %#", self.timesArray);
[self.tableView reloadData];
}
All I want eventually is an array of just the times. I am sorry if I am not being clear. I am trying to. Please let me know what information I can provide to paint a clearer picture

I'd save it as a string first
NSString *someString = [myArray objectAtIndex:index];
and then use something like NSMakeRange to get just that bit
[someString substringWithRange:NSMakeRange(11,18)];

Related

NSMutableArray objectAtIndex: Not Working

I am new to ios development. I am getting certain data from my web services in the form of Dictionary(Which contains a variable and an array of item dictionaries). I am successfully able to store data in userdefaults.
I form a new array named img_urls for a specific key from each item dictionary using for loop.
My problem is: when i access this array using [ img_urls objectAtIndex:0] , i get complete array as output rather than getting value only at 0th index. And giving [img_urls objectAtIndex:1] gives me NSRangeException.
Here is my code:
NSDictionary *restData=[[NSUserDefaults standardUserDefaults]valueForKey:#"Rest data"];
totalResult=[[restData valueForKey:#"totalResult"]intValue];
restaurants=[[NSArray alloc] initWithObjects:[restData valueForKey:#"restaurants"], nil ];
for(NSDictionary *item in restaurants)
{
[img_urls addObject:[item valueForKey:#"profileImage"]];
}
NSLog(#"REST NAMES%#",[img_urls objectAtIndex:0]);
Any help would be appreciated. Thanks in advance!
Change the method like this below:-
[[NSArray alloc] initWithObjects:[restData valueForKey:#"restaurants"], nil ]to
//Modified below
[[NSArray alloc] initWithArray:[restData valueForKey:#"restaurants"]]
First thing, Did you have analyzed an array, Try like this below:-
img_urls=[NSMutableArray array];
NSDictionary *restData=[[NSUserDefaults standardUserDefaults]valueForKey:#"Rest data"];
totalResult=[[restData valueForKey:#"totalResult"]intValue];
restaurants=[[NSArray alloc] initWithObjects:[restData valueForKey:#"restaurants"], nil ];
for(NSDictionary *item in restaurants)
{
[img_urls addObject:[item valueForKey:#"profileImage"]];
}
//Check first array count
if ([img_urls count] > 0)
{
NSLog(#"REST NAMES%#",[img_urls objectAtIndex:0]);
}
You are giving array([restData valueForKey:#"restaurants"]) as a object to restaurants array while initializing so you will get the whole array when getting by using objectAtIndex:0
NSDictionary *restData=[[NSUserDefaults standardUserDefaults]valueForKey:#"Rest data"];
totalResult=[[restData valueForKey:#"totalResult"]intValue];
restaurants=[[NSArray alloc] initWithArray:[restData valueForKey:#"restaurants"]];
for(NSDictionary *item in restaurants)
{
[img_urls addObject:[item valueForKey:#"profileImage"]];
}
NSLog(#"REST NAMES%#",[img_urls objectAtIndex:0]);

Parsing twitter-json in iPhone app

I used to have trouble parsing json, before I found a really good tutorial which I could follow. When I have been building my own webservices to parse json from I have followed the same steps, but now when I'm trying to parse twitters json-feed I'm drawing blanks. Here's my code.
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* itemNumber = [json objectForKey:#"posts"]; //2
NSUInteger numObjects = [itemNumber count];
arrayTweets = [[NSMutableArray alloc] init];
arrayTimes = [[NSMutableArray alloc] init];
if (numObjects != 0) {
int i = 0;
do
{
NSDictionary* loan = [itemNumber objectAtIndex:i];
NSString* text = [(NSDictionary*)loan objectForKey:#"text"];
[arrayTweets addObject:text];
NSString *time = [(NSDictionary*)loan objectForKey:#"created_at"];
[arrayTweets addObject:time];
i++;
} while (i < numObjects);
} else {
NSLog(#"Nej");
}
[tableTweet performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:NO];
Notice the "NSArray* itemNumber = [json objectForKey:#"posts"];". Since my old json-feed used to look something like this...
{"status":"ok","count":4,"count_total":4,"pages":1,"posts":[{"id":58,"type":
it was working since I had the "posts" before :[, but now with the twitter feed it just starts right into:
[{"created_at":"Mon Aug 06 19:16:42 +0000 2012","id":232555817835048961,"...
And I have no idea what to do. I realize this is stupid, but I don't think I'm going to learn unless someone explains it to me.
Any help appreciated!
Aah, there is a small problem with your code. The root object of your previous feed used to be a dictionary. You can see this by the { sign at the beginning. Your new feed instantly gives you an array back [. So you don't have to parse your data as a dictionary but as as NSArray. Without further ado, explanation here: https://stackoverflow.com/a/8356919/341358

help on sorting NSMutableDictionary strings that are URL images

i want to populate the tablecell with title and imageurl from xml list.
i manage to store the title (NSMutableDictonary *sections )and imageURL (NSMutableDictonary *sectionsImg) into 2 NSMutableDictionary respectively.
/*******This is in viewDidLoad***/
Directory *allDirectory = [appDelegate.directories objectAtIndex:0];
for (allDirectory in appDelegate.directories)
{
NSDictionary *dica = [NSDictionary dictionaryWithObject:allDirectory.dirTitle forKey:#"dirTitle"];
NSDictionary *dico = [NSDictionary dictionaryWithObject:allDirectory.imageURL forKey:#"imageURL"];
[dirName addObject:dica];
[dirImage addObject:dico];
//NSLog(#"dic of items : %#",dirImage);
}
for (allDirectory in appDelegate.directories)
{
//retrieve the first letter from every directory title (dirTitle)
NSString * c = [allDirectory.dirTitle substringToIndex:3];
NSString * m = allDirectory.imageURL;
found = NO;
find = NO;
for (NSString *str in [self.sections allKeys])
{
if ([str isEqualToString:c])
{
found = YES;
}
}
for (NSString *stra in [self.sectionsImg allKeys])
{
if([stra isEqualToString:m])
{
find = YES;
}
}
if (!found)
{
[self.sections setValue:[[NSMutableArray alloc]init] forKey:c ];
[self.sectionsImg setValue:[[NSMutableArray alloc]init] forKey:m];
}
if (!find)
{
[self.sectionsImg setValue:[[NSMutableArray alloc]init] forKey:m];
}
}
for (NSDictionary *directory in dirName)
{
[[self.sections objectForKey:[[directory objectForKey:#"dirTitle"] substringToIndex:3]] addObject:directory];
//NSLog(#"hehehe have : %#",sections);
}
for (NSDictionary *directoryImg in dirImage)
{
//[[self.sectionsImg objectForKey:[[directoryImg objectForKey:#"imageURL"] substringFromIndex:0]] addObject:directoryImg];
[[self.sectionsImg objectForKey:[directoryImg objectForKey:#"imageURL"]] addObject:directoryImg];
//NSLog(#"HOHOHO have : %#",sectionsImg);
}
And on cellForRowAtIndexPath i declare a dictionary
NSDictionary *dictionary = [[self.sections valueForKey:[[[self.sections allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
cell.textLabel.text = [dictionary objectForKey:#"dirTitle"];
but when i tried to declare a dictionary for imageURL
NSDictionary *dictionaryImg = [[self.sectionsImg valueForKey:[[[self.sectionsImg allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
it gives me a error :
Terminating app due to uncaught exception 'NSRangeException', reason: '* -[NSMutableArray objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
any idea why? the logic is supposed to be the same where xml title and url can be retrieve and be displayed. Title is retrievable but imageURL is not. Help is deeply appreciated !
You are trying to sort an array... except for the fact your array isn't an array, but a NSDictionary.
Your code isn't the best at the moment. Your getting the idea of Dictionaries wrong and may be confusing them with arrays, so my best guess is your quite new to programming into objective-c.
You have two lists of things, if I'm not mistaken. The first list is the list of names, and the second list is an image corresponding with that name.
Below I'm going to do two things:
Firstly, I'm giving you two ways on how to fix your problem. It has a sample code included and gives you a small explanation with it. The possibility exist you don't understand parts of what I describe. In that case, you should;
Check out the link I described below the two solutions. It has a tutorial which makes you understand everything about arrays, dictionaries, tables and, as a bonus, XML-parsing.
So, in my opinion, you can do two things:
The first one is using an array of NSDictionaries. You'd be using a code which looks like:
NSMutableDictionary *itemOne = [[NSMutableDictionary alloc] init];
NSMutableDictionary *itemTwo = [[NSMutableDictionary alloc] init];
NSMutableArray *listOfAll = [[NSmutableArray alloc] init];
NSString *itemOneName = [[NSString alloc] initWithFormat:#"This is picture 1"];
NSString *itemTwoName = [[NSString alloc] initWithFormat:#"This is picture 2"];
NSData *imageOneData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: #"http://myurl/mypic1.jpg"]];
NSData *imageTwoData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: #"http://myurl/mypic2.jpg"]];
UIImage *itemOneImage = [UIImage imageWithData: imageOneData];
UIImage *itemTwoImage = [UIImage imageWithData: imageTwoData];
[itemOne setObject:itemOneNameString forKey:#"Name"];
[itemOne setObject:itemOneImage forKey:#"Image"];
[itemTwo setObject:itemTwoNameString forKey:#"Name"];
[itemTwo setObject:itemTwoImage forKey:#"Image"];
[listOfAll addObject:itemOne];
[listOfAll addObject:itemTwo];
Anything can be filled using that array. Just use something with a for-loop to iterate through your array.
for (int i = 0; i < [listOfAll count]; i++)
{
NSMutableDictionary *currentItem = [[NSMutableDictionary alloc] initWithDictionary:[listOfAll objectAtIndex:i]];
//Do something with that current item
}
You can also use that index in your tableView. In that case, you have to use your variable section instead of i to get your desired index.
The second one is using two arrays. Imagine you get an image named imageOne with the text imageName. Then you should use:
NSMutableArray *nameList = [[NSMutableArray alloc] init];
[nameList addObject: imageName];
NSMutableArray *imageList = [[NSMutableArray alloc] init];
[imageList addObject: imageOne];
If you want to use a certain item out of those lists, you just have to use the same indexnumber.
For example:
[theTitleLabel setText:[[NSString alloc] initWithFormat:#"%#", [nameList objectAtIndex:x]]];
[theImageView setImage:[imageList objectAtIndex:x]];
Make sure the x's are the same number.
I understand this is all a lot of information, especially if you're new to Objective - C. A tutorial exists which gives you a lot of information about how to use arrays, dictionaries and table views. As a bonus, you get to know a little about XML-parsing.
I suggest you walk through that tutorial and do everything and read everything it says. This should give you a nice start into the world of programming in iPhones.
Good luck!

How to dissect and reorganize info in an NSDictionary

So I have an array of NSDictionaries, each NSDictionary has a bunch of key/value pairs pertaining to aspects of a photo (from Flickr).
I'm making an app that has a UITableViewController whose cells should be each of the different categories of the photos. So in pseudocode, I'm trying to construct a new NSDictionary (with keys being categories of photos, values being the NSDictionaries of the photos that contains that key). I'm iterating through each NSDictionary in the initial array, getting the category tags, and saying, if my new NSDict doesn't contain this key, make a new key to an empty array. Then add the current NSDict to that array. I'm getting consistent errors, not sure why.
Here's the diluted code.
photoList = [FlickrFetcher photosWithTags:[NSArray arrayWithObjects: #"CS193p_SPoT", nil]];
NSLog(#"%#", photoList);
categories = [[NSDictionary alloc] init];
NSArray *temp = [[NSArray alloc] init];
for (id obj in photoList) {
temp = [[obj objectForKey:#"tags"] componentsSeparatedByString:#" "];
for (id string in temp) {
if (![categories objectForKey:string]) {
NSMutableArray *arr = [[NSMutableArray alloc] init];
[categories setObject:arr forKey:string];
//[arr release];
}
NSMutableArray *photos = [categories objectForKey:string];
[photos addObject:obj];
[categories setObject:photos forKey:string];
}
}
Thanks!
NSDictionary doesn't have a method setObject:forKey:. You need an NSMutableDictionary.
self.categories = [NSMutableDictionary dictionary];
Other than that, please do use Joost's excellent rewrite of your code.
SIGABRT, just so you know, most likely means that an assertion somewhere failed. In this case, it may be an assertion all the way down in CoreFoundation*; CF checks for mutability when you try to access a dictionary like that and causes an interrupt if the object isn't mutable.
*I have just learned about the CF source's availability recently and have been looking through it, so this may be just "new thing" bias and incorrect.
I don't notice any errors (syntax-errors, that is) in your code, however here is an updated piece of code which has been implemented a bit cleaner (and without memory leaks)
self.photoList = [FlickrFetcher photosWithTags:[NSArray arrayWithObjects: #"CS193p_SPoT", nil]];
NSLog(#"%#", photoList);
self.categories = [NSDictionary dictionary];
for (NSDictionary *obj in photoList) {
NSArray *temp = [[obj objectForKey:#"tags"] componentsSeparatedByString:#" "];
for (NSString *string in temp) {
NSMutableArray *photos = [categories objectForKey:string];
if (!photos) {
photos = [NSMutableArray array];
[categories setObject:photos forKey:string];
}
[photos addObject:obj];
}
}
If it's not working please tell us the exact warning, and were it is caused.

Adding 2 keyvalues to list from JSON object

I want to append 2 key values from JSON object to my list in iPhone app. Below is my code for that,
SBJsonParser *jsonParser = [[[SBJsonParser alloc] init] autorelease];
NSString *jsonString=[[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://test/json/json_data.php"]];
id response = [jsonParser objectWithString:jsonString error:NULL];
NSDictionary *feed = (NSDictionary *)response;
list = (NSArray *)[feed valueForKey:#"fname"];
the above code properly displays the value from fname but what do i do if i want to add lname to it. for eg, my object is
[{"fname":"Bill","lname":"Jones"},{"fname":"John","lname":"Jacobs"}]
i want to display names as Bill Jones, John Jacobs and so on in the list. Currently it only displays Bill, John..I tried doing something like #"fname"#lname but it wont work..Can anybody please help me..
An observation: the response from the JSON parser is not a dictionary, but an array given the string you pass in. Your code works because -valueForKey: is something an array will respond to. The array sends -valueforKey: to each element and builds an array out of the responses.
There are two ways you can do what you want (at least)
Iterate through the array explicitly
NSMutableArray* list = [[NSMutableArray alloc] init];
for (id anObject in response)
{
[list addObject: [NSString stringWithFormat: #"%# %#",
[anObject objectForKey: #"fName"],
[anObject objectForKey: #"lname"]]];
}
Add a category to NSDictionary
#interface NSDictionary(FullName)
-(NSString*) fullName;
#end
#implementation NSDictionary(FullName)
-(NSString*) fullName
{
return [NSString stringWithFormat: #"%# %#",
[self objectForKey: #"fName"],
[self objectForKey: #"lname"]];
}
#end
Then your existing code changes to
list = (NSArray *)[feed valueForKey:#"fullName"];