Filling UITableview with NSMutableArray - iphone

Trying to fill my UItableview with my Array. I would like to match a object in my array to the correct cell.
My array is as follows.
(
(
{
cost = 160;
height = 1;
room_number = 1;
square_size = 1;
title = "TIMBER BLINDS";
width = 1;
}
),
(
{
cost = 170;
height = 1;
room_number = 2;
square_size = 1;
title = "ROMAN BLINDS";
width = 1;
}
)
My question is how do i match the correct title to the cell based on the room_number in my array?
Thanks

It seems like you are having array of array which contains dictionary so firstly fetch the object from an array by indexPath.row. The fetched object is also an array. Fetch dictionary object from it by objectAtIndex. Now that you have accessed dictionary so you can access your key value.
NSMutableArray *fetchedArray= [yourArray objectAtIndex:indexPath.row];
NSDictionary *fetchedDictionary = [fetchedArray objectAtIndex:0];
NSNumber *roomNumber= [fetchedDictionary valueForKey:#"room_number"];
if([roomNumber intValue] == indexPath.row) {
[cell setTextLabel:[fetchedDictionary valueForKey:#"title"]];
}

Assuming your array is self.tableContent
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *object = self.tableContent[index.section][index.row];
..... some cell code
cell.title = object[#"title"];
}

It is dictionary of array of array
you can get value of "room_number" by
NSString *room_number = [[[myarray1 objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:#"room_number"]

() -- this represents array
{} -- this represents dictionary
So you can see you have an array of arrays and each array contains a single object and i.e a dictionary.
In terms of Objective C, it is like this:
NSDictionary *dict1 = //first dictionary
NSDictionary *dict2 = //second dictionary
NSArray *mainArray = [NSArray arrayWithObjects: [NSArray arrayWithObject:dict1],[NSArray arrayWithObject:dict2], nil];
To retrieve value inside key title from dictionary and display that in TableView:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
// other code to set up cell
NSDictionary *array =[[mainArray objectAtIndex:indexPath.row] objectAtIndex:0];
cell.textLabel.text = [array objectForKey:#"title"];
return cell;
}

Related

-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x8943940 while parsing JSON Page to UITableView

I have been through many links and fortunately I got many similar links but nothing worked Out.
my array is appearing like this in Output, using NSLog()..
products = (
{
cid = 1;
name = "hello world";
},
{
cid = 2;
name = "It is an array";
},
{
cid = 3;
name = "error error";
},
{
cid = 4;
name = "OMG! still same";
},
{
cid = 5;
name = "any help";
...
...
},
{
cid = 130;
name = "How is the work going on.";
},
{
cid = 131;
name = "Had a nice lunch";
}
);
success = 1
Code to parse JSON, where "news" is an Array var..
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
news = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"Feeds...%#",news);
[myTableView reloadData];
}
Code to display table row, here in "news" value is being displayed by NSLog(); Error comes for NSDictionary.
-(UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(#"=====%#====",news);
NSDictionary *myDict = [news objectAtIndex:indexPath.row];
NSArray *myArray = [myDict objectForKey:#"name"];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MainCell"];
if (cell==nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"MainCell"];
}
for (NSString *str in myArray) {
cell.textLabel.text = str;
}
return cell;
}
I am not able to find what i'm missing here.., Please help me out.
Thank you in advance.
Your JSON structure is something like this:
Dictionary-->Array-->Object (Dictionary).
So you need to do:
Extract the Array from the dictionary using the key product
Extract an object(Dictionary) from the array using the index
Get the name from the dictionary object using the key name
Instead of this:
NSDictionary *myDict = [news objectAtIndex:indexPath.row];
NSArray *myArray = [myDict objectForKey:#"name"];
Use:
NSArray *myArr = [news objectForKey:#"products"];
cell.textLabel.text = [[myArr objectAtIndex:0] objectForKey:#"name"];
Edit
Also change your numberOfRowsInSection like:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[news objectForKey:#"products"] count];
}
news is a NSDictionary, and a dictionary does not have a method objectAtIndex:
You have to use instead [news objectForKey:...];
[news objectAtIndex:indexPath.row];
NSMutabledictionary is indexpath.row so add first news in array and that array name add in
your code and you get nothing an
Put NSDictionary in Array then use it in Table method
NSMutableArray *result=[[NSMutableArray alloc] init];
result = [googleResponse valueForKey: #"products"];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSMutableDictionary *dt = [result objectAtIndex:indexPath.row];
}
It will Help you !!!!!

UITableView not reversing

I'm working on information retrieval where in the latest information in on top of UITableView. The code goes like this.
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
LoanModel* loan = _feed.products[indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" ];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:#"Cell"];
}
NSString *myString = [NSString stringWithFormat:#"%#",[loan name]];
NSArray *myWords = [myString componentsSeparatedByString:#","];
NSMutableArray *reversed = [NSMutableArray arrayWithCapacity:[myWords count]];
NSEnumerator *enumerator = [myWords reverseObjectEnumerator];
for (id element in enumerator) {
[reversed addObject:element];
}
NSMutableString *reverseString = [reversed componentsJoinedByString:#","];
cell.textLabel.text = reverseString;
return cell;
}
I'm getting the JSON object which contain two fields cid and name respectively. I'm showing only the name is tableview. But I want to show it in reverse i,e last update should show at first. But above code showing the content in reverse. IF "hello" is the content, then it shows "olleh". Please suggest me how to get the UITableView in reverse list. I'm a newbie to iOS.
If you want to have the reversed order of cells / objects they represent, you have to change
LoanModel* loan = _feed.products[indexPath.row];
to
LoanModel* loan = _feed.products[_feed.products.count - 1 - indexPath.row];
assuming that _feed.products is an NSArray.
The array you are using to display the the data in tableView, you'll need to reverse that and then display the data in tableView
NSArray* reversed = [[myArray reverseObjectEnumerator] allObjects];
you can use this to make your array objects order in reverse.
Try This:
NSArray* reversedArray = [[myWords reverseObjectEnumerator] allObjects];

NSMutableArray insertObject at random indexes

I have a NSDictionary that contains objects and keys. The Keys hold a Name and number. I would like to insert those objects into a NSMutableArray by using insertObject: atIndex: . Object being the name and the number is the index I would like to place the object in. I now know that NSMutableArrays are able to insert objects at index:6 if there is no 1-5 so how do I make this possible? Any suggestions are very appreciated!
Example Dictionary [dict objectForKey:#"array"]:
preferences as whole (
{
Name = PowerDown;
btnIndex = 3;
},
{
Name = ClearCache;
btnIndex = 5;
},
{
Name = KillBGApps;
btnIndex = 6;
},
{
Name = InfoPanel;
btnIndex = 2;
},
{
Name = Lock;
btnIndex = 4;
},
{
Name = Reboot;
btnIndex = 0;
},
{
Name = Respring;
btnIndex = 1;
}
)
What I have so far but crashes when adding objects out of bounds of the array
-(void)loadArray{
self.buttons = [NSMutableArray array];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
tempArray = [buttonsPrefs objectForKey:#"buttonsToOrder"];
for(NSDictionary * dict in tempArray)
{
if (dict) {
NSString *btnName = [dict objectForKey:#"Name"];
NSString *btnIndex = [dict objectForKey:#"btnIndex"];
NSUInteger index = [btnIndex integerValue];
NSLog(#"Name = %#",btnName);
NSLog(#"at index %i",index);
[self.buttons insertObject: btnName atIndex: index];
}
}
}
EDIT: These values "indexes" for the names with change when a user moves the cell
- (void) tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath
*)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
NSUInteger fromIndex = [fromIndexPath row];
NSUInteger toIndex = [toIndexPath row];
if (fromIndex == toIndex)
return;
NSMutableDictionary *selectedButton = [[[_buttons objectAtIndex:fromIndex] retain]
autorelease];
[_buttons removeObjectAtIndex:fromIndex];
[_buttons insertObject:selectedButton atIndex:toIndex];
//[buttonsPrefs setObject:_buttons forKey:#"buttonsToOrder"];
//[buttonsPrefs writeToFile:[self getFilePath] atomically: YES];
}
Try to fill your target array with some dummy data according to yourDict count like this:
for (int i=0, i<[yourDict count], ++i){
[yourArray addObject:#"dummyData"];
}
And when you will need to insertObject do this:
for(NSDictionary * dict in tempArray)
{
if (dict) {
NSString *btnName = [dict objectForKey:#"Name"];
NSString *btnIndex = [dict objectForKey:#"btnIndex"];
NSUInteger index = [btnIndex integerValue];
[yourArray insertObject:btnName atIndex:index];
[yourArray removeObjectAtIndex:index+1];
}
}
NSMutableArray insertObject: atIndex:
as per apple docs `
"Note that NSArray objects are not like C arrays. That is, even though
you specify a size when you create an array, the specified size is
regarded as a “hint”; the actual size of the array is still 0. This
means that you cannot insert an object at an index greater than the
current count of an array."
Can only fill within valid array value set.Two things you can do.
Sort and fill the array
Fill the array with some default object like a string(cannot be nil) and then replace it.This option is valid if you are filling all the values in array because when used later you have to check weather the value is right there or the default value is in that position

Parsing json string in iOS Objective C

I am trying to build my first iOS app that parses json from a web service.
In my .h file i create an array
NSArray *items;
In my .m file i call the website and store the data into the array. This all goes fine except eventually I am trying to display the data in a uitableview.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"ItemsCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSLog(#"%#",items);
NSDictionary *item = [items objectAtIndex:indexPath.row];
NSString *title = [item objectForKey:#"title"];
cell.title.text = title;
return cell;
}
The nslog of items produces:
{
category = code;
keyword = "";
limit = 20;
lowPrice = "";
page = 0;
products = (
{
description = "...";
mobileFriendly = 1;
popularity = 2021;
productId = code;
title = "title";
}, and so on...
)
I am getting an error trying to do NSDictionary *item = [items objectAtIndex:indexPath.row]; It says doing objectAtIndex:indexPath.row is invalid.
What am I doing wrong?
Thanks for your help!
The value stored in items is an instance of NSDictionary, but you're sending it an NSArray message. Also, the code you posted is referring to gift and ignoring the item anyway.
The array you're looking for is actually stored under the key products inside the items dictionary, so you need to do something like this:
NSArray *products = [items objectForKey:#"products"];
NSDictionary *product = [products objectAtIndex:indexPath.row];
// Then use the product, instead of using 'gift' (whatever that is).
NSString *title = [product objectForKey:#"title"];
items is not a NSArray - it is a NSDictionary. so it has no objectAtIndexPath: method.

Static Table View

I am creating a static table view (must be compatible with iOS 4 - so I can't use iOS 5's method).
The way I have it is that I have two sections; the first has one cell, and the second has two cells. I made two arrays, one with the title of the only cell in the first section, and the second with both titles for both cells in the second section. So my dictionary looks like this:
(NSDictionary *) {
First = (
Title1 < --- Array (1 item)
);
Second = (
"Title1", < --- Array (2 items)
Title2
);
}
The issue I have is that I need to return number of rows in a section using tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section. So my question is, how do I retrieve the section from the dictionary using NSInteger section? I would also have to do the same thing in tableView:cellForRowAtIndexPath.
Thank you
If you don't understand how dictionaries work, I'd recommend simplifying the problem. Create one array for each section, then inside your delegate methods use a switch() statement to call [array count] for the row count etc. For the section count you could still use the original dictionary with [[dictionary allKeys] count].
EDIT:
I just saw #fzwo recommends the same thing in two comments
Your best bet is an array of arrays, as has been mentioned. To avoid the complexity with dictionaries, create two NSArray ivars for the table data and the section titles.
// in viewDidLoad
tableData = [NSArray arrayWithObjects:
[NSArray arrayWithObjects:
#"Row one title",
#"Row two title",
nil],
[NSArray arrayWithObjects:
#"Row one title",
#"Row two title",
#"Row three title",
nil],
nil];
sectionTitles = [NSArray arrayWithObjects:
#"Section one title",
#"Section two title",
nil];
// in numberOfSections:
return tableData.count;
// in numberOfRowsInSection:
return [[tableData objectAtIndex:section] count];
// in titleForHeaderInSection:
return [sectionTitles objectAtIndex:section];
// in cellForRowAtIndexPath:
...
cell.textLabel.text = [[tableData objectAtIndex:indexPath.section]
objectAtIndex:indexPath.row];
You could use other objects instead of the row titles if you need more data available to your cell.
To get the number of rows in your section you can use the following:
tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSString *key = [[dictionary allKeys] objectAtIndex: section];
return [[dictionary objectForKey:key] count];
}
And to get the cell value:
tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *key = [[dictionary allKeys] objectAtIndex: indexPath.section];
NSArray *values = [dictionary objectForKey:key];
NSString *value = [values objectAtIndex: indexPath.row];
// code to create a cell
return cell;
}