UISearch rearrange the indexpath.row - ios

I have a UiSearchBar implemented in my TableView, and I also have two NSArrays, one for title and one for description. When I search through the array of the titles, it returns the right search, but when I click on a row that the search came with, I get "row 0" if I click on the first row. My question is how to make a connection between the two arrays so that when the search rearranges the titles based on the user search, the description array corresponds to the same row the title is at.

Simply do not use two NSArrays, but just one with custom NSObject objects:
#interface SomeObject : NSObject {
NSString *_title;
NSString *_description;
}
- (BOOL)matchesKeywords:(NSString *)keywords;
#end
Then you have all your information stored in one class, the way Obj-C is meant to be. You can easily perform the search because the objects itself sort of knows whether it matches a given keyword, so when you'd like to change SomeObject you can easily manage those changes in the class itself.

I did merge the two arrays into one, but that made the tableviewcell load alot slower because the cell is holding both, the title and description

I had this problem once So for the quick fix I did this:
In the header:
BOOL usingFilterArray;
Where you switch between the complete dictionary and the filtered one simply set the above BOOL to NO and YES respectively.
then in didSelectRowAtIndexPath use "if" statement to check the sate of the usingFilterArray.
Rest should be pretty easy. (Let me know if you still need help)
Just one thing when you perform the search after the filter Dictionary is hydrated if you cancel the search you need to make sure to run this or your app is going to crash as the hydrated dictionary will not have any object in it. (I assumed you cleaned the filtered Dictionary)
- (void) searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller {
[self.tableView reloadData];
}
Mate this is just a quick fix.

Related

Add row programmatically in static UITableView

I have a static UITableView as shown in the first image, but now I need to add a row with a Button that when I touch it adds a dynamic cell to the table as shown in the second image, the issue is that I can't add new cells to a static UITableview.
What would be the best practice to accomplish this?
Basically static TableView is not supposed to be changed at runtime (except cell content). This is clearly mentioned in docs:
Use static cells when a table does not change its layout, regardless of the specific information it displays.
The best practice in this case is to create a dynamic TV and populate it with appropriate amount of cells. You'll need to use DataSource delegate to do so. DataSource itself is typically done through dictionaries or arrays.
E.g. you have a dict 'phoneNumbers' and a button that is supposed to add a new one.
First, you add a selector to the button in cellForRowAtIndexPath: via tag for example. Then button action is going to look like:
-(void)yourButtonClicked:(UIButton*)sender
{
[self.phoneNumbers setObject:phoneNumber forKey:numberKey];
[self.tableView reloadData];
}
//Swift
func yourButtonClicked(sender: UIButton) {
self.phoneNumbers["numberKey"] = phoneNumber
self.tableView.reloadData()
}
(sorry it's Obj-C but I'm quite sure swift isn't much different at this point)
reloadData is needed to refresh TableView layout after changes to DataSource objects are made. It's quite close to 'redraw' in this case.
On the image from Contacts App you showed object is '(555)555-5555' NSString and key is probably 'other'. You can use and store these any way you like
So after all you only need to setup numberOfRowsInSection: so that for section where you want to add cells it returns the count of objects in dictionary phoneNumbers

Set hidden data to uitableview cell

I searched a bit here and on google, but I couldn't really find unearthing that I could clearly understand. Basically what I'd like to do is display a list of names, then when clicking on the table add the ID of those names to another array, along with their ID. The solution I'm working on at the moment is based on nested NSMutableArrays but I don't know if that's the best thing to do. I think it would be ideal to have another "field" to write on in the cell (by field I mean something like cell.text) so that I could store my hidden value.
Is there a way to do so?!
You need to adjust your thinking. Cocoa strongly follows the MVC (Model View Controller) design pattern, and you should learn to think that way.
In MVC, the model is the part of the program that stores your data. The View is what displays information to the user and interacts with the user.
The controller is the brains that serves as the control logic and feeds data back and forth between the model and the view.
In UIKit, objects with View in their name are view objects, and objects with controller in their name are controller objects. As a general rule the model object is up to you, as its application specific.
A table view is a view object. It doesn't store information, it presents it to the user and/or collects it from the user.
An array usually is the best choice for storing the data that gets presented in a table view. If you have a table view with multiple sections and multiple rows in each section than an array for each section, containing an array with data for each row is a good choice. Unless you have a sectioned table view forget about that however. It'll just confuse you.
For a "flat" table view with only one section, a single array is usually what you want.
How you store the data that you display in a cell is a design question. One easy answer is to use a dictionary for the data in each cell. So you wind up with an array of dictionaries.
If you're comfortable creating custom objects the a custom data storage object makes your code a little cleaner. However, you will probably want to implement the NSCoding protocol in your data objects so you can save them to disk easily.
Using an array to store the data for a cell is NOT a very good choice, because arrays use numeric indexes for their data. You might have a name that you want to display in your cell, and an image, and an employee ID, and a salary, and a few other things. What numeric indexes should you use for those values? Not clear. Now, if you use a dictionary, you can use meaningful keys:
cellData[#"name"]
cellData[#"imageName"]
or better yet, define constants for your keys:
#define kNameKey #"name"
#define kImageNameKey #"imageName"
then
cellData[kNameKey]
cellData[kImageNameKey]
That way you don't risk mis-typing the key string somewhere and introducing a bug that you have to go figure out.
If you're a beginner you might want to start out with an array of dictionaries. After you've used that approach for a while you might decide to migrate to custom data objects.
Let's assume we're using a dictionary to store the data for each cell from now on.
Now, to your question. It's perfectly ok to store more information in the dictionary for each cell than you display at any one time. The data isn't really hidden, it's just not (yet) displayed. Then, if the user takes an action that means you want to expose additional data, tell the table view to reload that cell. You might want to keep an array of info about the status of each cell (e.g. a bool that tells if the table view should display the salary info for each entry in your data array.) When the user does something that changes the info you want to display, change the appropriate setting in that index in the display status array and tell the table view to reload that cell. In your cellForRowAtIndexPath method, you would check the display status array for what to display for that cell, then fetch the appropriate data and install it into the cell (and clear out fields that should not be shown, since they might be left over from the last time the cell was used.)
If you have an array of dictionaries, then your cellForRowAtIndexPath method might look up the attributes of an entry like this:
- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger row = indexPath.row;
NSDictionary *rowData = dataArray[row]
NSString *name = rowData[kNameKey];
NSString *imageName = rowData[kImageNameKey];
}
Think more object-oriented, it'll make things like this a lot easier.
Make a class called Person with two properties: name and ID. Subclass UITableViewCell to take a list of Person, for which each name will be displayed. When the cell is clicked, add each Person to the appropriate location.
Here is a link for a tutorial on how to subclass youor own custom table view cell:
http://www.pumpmybicep.com/2014/07/21/designing-a-custom-uitableviewcell-in-interface-builder/
As for the Person class, create a new class of type NSObject called Person. In Person.h, add the following:
#property (nonatomic) NSString *name;
#property (nonatomic) int *ID;
- (id)initWithName:(NSString *)name ID:(int)ID;
And in Person.m, add the following:
- (id)initWithName:(NSString *)name ID:(int)ID {
if (self = [super init]) {
self.name = name;
self.ID = ID;
}
return self;
}
Now you can transfer data using Person.
Initialize:
Person *myPerson = [[Person alloc] initWithName:myName ID:1];
Get:
customCell.text = myPerson.name;
Transfer ID:
[clickedIDs addObject:[NSNumber numberWithInt:myPerson.ID]];
You could subclass a UITableViewCell and add an extra property
#property (nonatomic, strong) NSString *hidden;
for example. Then:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CustomUITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.text = #"Name";
cell.hidden = #"ID";
return cell;
}
That's how to do what you've asked, however it seems an odd request so you may want to consider if that's really the best way of achieving what you're trying to do. I'm not clear from your question what you've tried though.

Objective C MutableArray delete empty row

I have a problem with my tableview. When I tap the add button in my tableview it sends me to a textview where I can write a text. Then when I save it, it moves back to the tableview and create a new row with the text from the textview as title. If the textview is empty it saves it with no text, and create a row without a title in the table view.
I want to delete all rows without a title in the tableview. I save the text to a NSMutableArray named "savedText".
Here is some code I have tried:
if ([savedText containsObject:#""]) {
savedText=nil;
}
and this:
if ([savedText isEqualToArray:#""]) {
savedText=nil;
}
Nothing happens when I use this code.
Conny, one of us doesn't understand or is missing something here. It's probably me, but just to try to help out anyway.
As I understand it you're storing all the entered strings into the array named savedText and want to go through all the items in the array to check if they're empty and remove them from the array if they are. Is that correct?
GuybrushTheepwood is right in his comment, you could simply check before storing it in the array. If it's empty, just don't store it and you'll never have to make the processor work to remove it.
However, if you still want an algorithm for removing empty strings you'll need to try something else. Your first if block will get rid of the entire array if it contains something that's empty, and your second one should be giving a warning that the parameter isn't an NSArray*. Maybe your looking for something like this?
for (NSString* string in savedText) {
if ([string isEqualToString:#""]) {
[savedText removeObject:string];
}
}
// Potentially more code here? Like reloading the tableview?
But that'll only remove it from the array, you'll need more than that to update the view.

Editable UITableView design

I have a question regarding a design convention.. See I have this tableview filled with editable information. Editable as in changing the text in the right detail of the cell, not as in deleting or moving a cell. I wonder how to design/model this, the only Apple product that I know has this feature is the contacts app. The solution there is to make lots and lots of groups, but this does not fit my problem at all, partly since I already have groups. The simplest way would just be to have the right detail be a text field and enable it in edit mode, but that would of course be a stupid solution since no visual feedback is given..
Any ideas on how to design/model this, or how Apple would like to have it?
EDIT:
To be more clear in what I mean, this is a screenshot explaining what I have said. Once again, my problem is how to show the table cells when they are in edit mode. All values are changeable, and none of them have any kind of presets to choose from, they are all based on text written by the user. This part of the app is basically a CRM system, where you can edit all the information about yourself.
What you are trying to do is pretty standard for Dynamic Prototype cells (as opposed to the Static Cells you probably used to make that screenshot). You're best bet is probably going to be to just watch a couple of these tutorials.
To give a quick summary, you're going to put all the strings you want to show in the Value part of your screenshot into an NSArray. There are UITableViewDelegate and UITableViewDataSource methods that will automatically handle putting the ith item in the array into the ith cell (so the 3 item in the array will go into the 3rd cell, etc.). To allow the user to edit things, you're going to want to make a whole new second screen (this is where you're UITextfields will be). When the user goes back from the second screen to your table screen, you replace items in the array with whatever the user entered in the UITextfield, then tell the UITableViewDelegate methods to reload the table with the new Values.
Most of the tutorials I linked to probably aren't going to have anything about having multiple Groups, so I'll add a bit on that here (what follows will probably only make sense if you watch the tutorials first, so I'd suggest following along with the tutorials, then coming back here afterward and making the changes I'm about to suggest). The NSIndexPath that is sent to the tableView:cellForRowAtIndexPath method contains information on the cell row and section. Each "Group" is it's own section (I'm really not sure why Apple decided to use two different names for the same thing, but so it goes). The easiest way to do this is to have different arrays for each section (so you'll have lines for NSMutableArray *firstSectionArray = [[NSMutableArray alloc] init];, NSMutableArray *secondSectionArray = [[NSMutableArray alloc] init];, and so on). Then, at the very top of your tableView:cellForRowAtIndexPath method, you put some if statements in to see what section of the table you are "building", and use values from the correct array accordingly. Something like:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0)
{
// bunch of stuff from the tutorials here to create "cell"
[cell.detailTextLabel.text = firstSectionArray objectAtIndex:indexPath.row];
// bunch more stuff
}
else if (indexPath.section == 1)
{
// bunch of stuff from the tutorials here to create "cell"
[cell.detailTextLabel.text = secondSectionArray objectAtIndex:indexPath.row];
// bunch more stuff
}
// else if (keep going for however many sections you have)
return cell;
}

How do I display only a subset of a datasource in a UITableView?

I want to swap out the content of a tableview. The data source has elements with a flag that denotes whether or not they should be shown.
Ultimately, I want to be able to swap what is shown, depending on the flags. For now, though, I'll settle on an answer to the following.
How can my table display only a subset of the datasource?
I am not asking for a [tableView reload], which seems to be what most of my searches yielded. I want to show only some of the datasource items at a time based on a criteria (the flag, in this case).
As an example for clarity, here's a sample of the functionality.
We have 50 Friend elements in an array. It is the datasource for our table. When we load the app, all 50 friends are shown.
20 of those friends are marked as "Awesome" within the Friend class. When you tap the Awesome button, those 20 are shown in the table.
10 of them are marked as "Lame" within the Friend class. When you tap the Lame button, those 10 are shown in the table.
What methods do I need to look at to achieve that? TableView discussions are huge and I've been looking through bugs and errors without satisfying results, so far.
Keep two data structures. The first is the master set of data. The second contains just the data you want to display. Point the table to the second set of data.
Basically, when you want to reload the table with a different subset, create a new array, iterate the master data set and add just the objects you want to the new array.
SInce the second array just have references to the original objects from the master array, there is little extra overhead for this.
Update: To expand on the comment by Rob Napier, the master data structure I mentioned would be the "model" and the second data structure would be the data that backs the table's data source.
You can set up an NSPredicate to filter the values that will be returned by the fetchResults:
- (NSFetchedResultsController *)fetchedResults {
...
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"flag == %#", #"Awesome"];
[fetchRequest setPredicate:predicate];
...
This will only return those records that meet the criteria of the NSPredicate.

Resources