Passing array of objects to dynamic cells in Table view - ios

I have used a Table View with Dynamic Prototype cells.
I have created a sample row in the table view with four values of a quantity:
Title
Min Value
Max Value
Current value.
I have created Table view controller and table view cell classes for accessing those properties in my code.
Now I have to set the values dynamically. I can see people suggesting to pass array of values separately for each.
Like:
Array 1 for Title : which will display title for all items in the row
Array 2 for Min value and so on.....
Is there a way that we pass an array of objects to the table view and it creates the table.
Please suggest.

I can see people suggesting to pass array of values separately for each.
Don't do this it is very poor approach, instead create a single array of NSDictionnaries, for instance:
_listOfValue =
#[
#{#"Title":#"title 1", #"Min Value":#"0", #"Max Value":#"100", #"Current value":#"50"},
#{#"Title":#"title 2", #"Min Value":#"4", #"Max Value":#"90", #"Current value":#"60"},
#{#"Title":#"title 3", #"Min Value":#"6", #"Max Value":#"70", #"Current value":#"70"}
];
This will make it easy to retrieve the data you need since they are not separated.
In numberOfRowsInSection you can return [self.listOfValue count].
In cellForRowAtIndexPath or didSelectRowAtIndexPath you can easily get the dictionnary at the IndexPath then parse the value of each key.
//Get the specific value
NSDictionnary *valueDict = _listOfValue[indexPath.row];
//read data from value dictionary
valueDict[#"Title"];
//or the old syntax
[valueDict objectForKey:#"Title"];

No, you can't pass the array direct to the table. Your table view controller would usually maintain the array (often a single array containing dictionaries or custom class instances) and your code in the table view controller uses that array to configure the cells.

Related

Display correct objects/keys from array in string?

I'm trying to display items from an array in my tableView cells, in a string. Currently, I'm using these lines of code:
.m
id swaptime = self.filteredTotal[0][#"swaptime"];
NSString *test = swaptime;
...to grab the value located in swaptime, and display it in each of my cells. That said, in all of my cells, this line forces them all to display only the FIRST swaptime value - rather than the list of swaptime values from my array in their corresponding cells. Is this because of the [0] in my line (e.g. only grab the value located at 0)? If so, how should it be written instead so that all values are displayed?
I'm not sure of the answer since you have not provided all of your code, but if the code shown above is from the cellForRowAt method of the UITableView datasource, then this should work:
id swaptime = self.filteredTotal[indexPath.row][#"swaptime"];
(provided you do not intend on having more than 1 section)

How to add object / value to a certain element on NSMutableArray?

I only know method addObject, which is add object to the next element in the array. I want to be able to add / set / update object to an arbitrary position at the NSMutableArray, ex:
arr[105] = #(true);
arr[709] = #(30);
arr[1010] = #"Hello world!";
NSLog (#"%#", arr[1010]);
I have been trying something like this, but the next time I tried to retrieve the value, it says nil. How to do this? Thanks.
EDIT: last time I tried, it gave me error: index 1010 beyond bounds for empty array.
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. For example, if an array contains two objects, its size is 2, so you can add objects at indices 0, 1, or 2. Index 3 is illegal and out of bounds.
read more at https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/index.html
below method use for replace existing object at index with new object
[self.arr replaceObjectAtIndex:<#(NSUInteger)#> withObject:<#(nonnull id)#>]
below method use for insert new object at index
[self.arr insertObject:<#(nonnull id)#> atIndex:<#(NSUInteger)#>]
Ex:
if object already available at index and replace with new object
[self.arrayBuyers replaceObjectAtIndex:1010 withObject:#"Hello world!"]
add new object at index
[self.arr insertObject:1 atIndex:#"Hi"];

trying to populate a cell label with a string from an array

So, I have a cell with one label inside. I am trying to populate that label text with the various items in my array - all strings.
My array
var restauranttypelist: [String] = ["American", "Asian", "Bakery & Deli",
"Burgers", "Italian", "Mexican", "Seafood", "Steakhouse"]
and my cell label text
let type = restauranttypelist [indexPath.row]
var typecell = tableView.dequeueReusableCellWithIdentifier("cellone") as RestaurantTypeCell
typecell.restaurantTypeLabel.text = restauranttypelist.text
return typecell
I have tried a number of solution ranging from ".text" seen above, to ".String", to "restauranttypelist:indexPath.row" to no avail.
I suppose I have two questions. Am I setting up my array correctly? Do I need to insert the "[String]" portion after the variable name?
Finally, how would I be able to set the cell label to the numerous items I have in my array?
Thanks for any help... beginning.
Jon
In let type = restauranttypelist[indexPath.row] you're accessing a String from your Array and storing it in type. Therefore, all you need is typecell.restaurantTypeLabel.text = type.
There's nothing wrong with how you setup the array. You don't need the [String] type annotation since it can be inferred from the value you are assigning to it, but having it there does no harm.
Finally, this doesn't affect how your code works, but it's nice to know anyway:
Swift variable names follow the convention of starting with a lowercase character, and then capitalizing every subsequent word. Following that convention your variable names should be typeCell and restaurantTypeList.

iOS Select specific entries to display in table

I have an array, which contains multiple dictionaries.
Formatted like this:-
Array
- Index
- DOW = Weekday
- Index
- DOW = Weekend
- Index
- DOW = Weekday
I want to populate a table with data from only those dictionaries containing DOW = Weekday.
What is the quickest way of enumerating this?
Note that the data will be changed via filters, and then table reloaded.
You can filter your array using NSPredicate, like this:
NSArray *data = #[
#{#"Dow":#"Weekday", #"One":#"Two"} // Item 0
, #{#"Dow":#"Weekend", #"Three":#"Four"} // Item 1
, #{#"Dow":#"Weekday", #"Five":#"Six"} // Item 2
];
NSPredicate *pred = [NSPredicate predicateWithFormat:#"(Dow=='Weekday')"];
NSArray *res = [data filteredArrayUsingPredicate:pred];
The code above will keep NSArrays items 0 and 2, and remove item 1, because it does not contain an entry where #"Dow" is set to #"Weekday".
The data variable above represents the pre-filtered data in your example.
I'd suggest you read Apple UITableViewDataSource protocol guide here and perhaps this tutorial too.
Basically you'll want to -
Override numberOfSectionsInTableView: and return the number of sections in your table (0 if it's not relevant).
Ovveride tableView:numberOfRowsInSection: and here you can "apply" the needed filters on your dictionary and return the correct number of rows you actually want to display.
Next time you update the filters and call reloadTable again the above steps will filter the table correctly according to the new filters.

How to Search multiple NSArray from UITableView in IOS

What I want is to be able to search a UITableView, and have other arrays be narrowed down to the results of the cell's textlabel array. That probably just made no sense to no one. Here's an example.
An array called titleArray that fills the cell's textLabel:
"Toyota Yaris"
"Ford Escape"
"Ford F-150"
Another array called detailArray that fills the detail text label below the textLabel in a cell:
"Car"
"SUV"
"Truck"
When I search for "Ford" I want the UITableView to display the cells like this:
Cell 1: Ford Escape
SUV
Cell 2: Ford F-150
Truck
But it is displaying like this:
Cell 1: Ford Escape
Car
Cell 2: Ford F-150
SUV
Essentially it narrowed down the titleArray but not the detailArray so it is display objects 1 & 2 from titleArray but 0 & 1 from detailArray. If this confuses you please ask any questions!
For this you would be much better off having just one array. Two ways you could do this:
1) create a custom class (derived from NSObject) for the elements of your array, perhaps named Vehicle. Your vehicle class would have a 'name' property, and a 'type' property.
NSMutableArray *vehicleArray = [[NSMutableArray alloc] init];
Vehicle *myVehicle = [[Vehicle alloc] init];
myVehicle.name = #"Ford Escape";
myVehicle.type = #"SUV";
[vehicleArray addObject:myVehicle];
2) have the elements in your array be of type NSDictionary. Each dictionary would have a key value pair for name and type.
NSMutableArray *vehicleArray = [[NSMutableArray alloc] init];
NSDictionary *myVehicle = [[NSDictionary alloc] initWithObjectsAndKeys:#"Ford Escape", #"name", #"SUV", #"type", nil];
[vehicleArray addObject:myVehicle];
In your code, you are likely creating UITableViewCell object in a message named tableView:cellForRowAtIndexPath:. I would review this code for your issue. When you create/retrieve the UITableViewCell, you will then fill in the title and detail (check this in the debugger). I note that the example you are following is creating a pared down array of items in response to your search argument. It seems most likely that you will need to pare down the detail array at the same time you pare down the title array. You may also need to search in your detail array (depending on how you want your app to function). This could complicate your search logic some.
//Possible search logic
for (int iii = 0; iii < titleArray.count; iii++) {
if (<titleArray matches search string>) {
[titlesToDisplay addObject:[titleArray objectAtIndex:iii]];
[detailsToDisplay addObject:[detailArray objectAtIndex:iii]];
//Assuming that you have titles and details in corresponding slots.
}
}
Now when you set the title and detail settings for your UITableViewCell, you should count entries in titlesToDisplay and retrieve entries from titlesToDisplay and detailsToDisplay.

Resources