Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

iphone - How to save nsdictionary of a subview to a mainview based off tableviewcell selection

I am currently parsing some xml that looks like this

<Rows>
<Row MANUFACTURERID="76" MANUFACTURERNAME="Fondont" ISMANU="F" ISAUTO="F"/>
<Row MANUFACTURERID="18" MANUFACTURERNAME="Anti" ISMANU="T" ISAUTO="T"/>
</Rows>

I parse it so that there is an array of dictionaries (each dictionary has the four values of the Row in it).

I then pass ManufacturerName to my startSortingTheArray method like this

if (dataSetToParse == @"ICMfg") // ICMfg is a string passed to this view from the parent view cell selection enabling me to pass different data sets to this view
    {
       //Filter results (ISAUTO = T)
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K like %@",@"ISAUTO",@"T"];
        NSArray *filteredArray = [myDataArray filteredArrayUsingPredicate:predicate];
        //Passes Manufacturer strigs over to startSortingtheArray method
        [self startSortingTheArray:[filteredArray valueForKey:@"MANUFACTURER"]];
    }

So from here all of the ManufacturerNames are sent to my method as an array of strings. I then use this array to set up all of my sections / index-scroller. The method below shows how I am doing this.

//method to sort array and split for use with uitableview Index
- (IBAction)startSortingTheArray:(NSArray *)arrayData
{
    //If you need to sort incoming array alphabetically use this line of code
    //TODO: Check values coming in for capital letters and spaces etc
    sortedArray = [arrayData sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    //If you want the standard array use this code
    //sortedArray = arrayData;

    self.letterDictionary = [NSMutableDictionary dictionary];
    sectionLetterArray = [[NSMutableArray alloc] init];

    //Index scrolling Iterate over values for future use
    for (NSString *value in sortedArray) 
    {
        // Get the first letter and its associated array from the dictionary.
        // If the dictionary does not exist create one and associate it with the letter.
        NSString *firstLetter = [[value substringWithRange:NSMakeRange(0, 1)] uppercaseString]; //uppercaseString puts lowercase values with uppercase

        NSMutableArray *arrayForLetter = [letterDictionary objectForKey:firstLetter];
        if (arrayForLetter == nil) 
        {
            arrayForLetter = [NSMutableArray array];
            [letterDictionary setObject:arrayForLetter forKey:firstLetter];

            [sectionLetterArray addObject:firstLetter]; // This will be used to set index scroller and section titles
        }
        // Add the value to the array for this letter
        [arrayForLetter addObject:value];
    }      
    //Reload data in table
    [self.tableView reloadData];
}

from here I do several things to do with setting up the tableview after [self.tableView reloadData]; is called, The main thing being is that I set the cell up with the string values of the array.

//Display cells with data
    NSArray *keys = [self.letterDictionary objectForKey:[self.sectionLetterArray objectAtIndex:indexPath.section]];
    NSString *key = [keys objectAtIndex:indexPath.row];

    cell.textLabel.text = key;

when the cell is then selected the string value inside the cell is then sent back to the main view and used later as a search parameter... The thing being is that I am setting up several parameters that will be used as one search string.

Looking back at the XML I parsed

<Rows>
    <Row MANUFACTURERID="76" MANUFACTURERNAME="Fondont" ISMANU="F" ISAUTO="F"/>
    <Row MANUFACTURERID="18" MANUFACTURERNAME="Anti" ISMANU="T" ISAUTO="T"/>
</Rows>

These are the values of columns inside an SQl table that has a keyvalue MANUFACTURERID that is also found in other tables that I parse. I would like to use these key values to restrict/refine other queries but I just cannot figure out how to pass them to my parentview where I set up all of the search parameters, that is my question how can I save the dictionary of values that is related to the users tableview selection from the subview. So that I can then pass one or some of those values back to the subview of a different dataset to restrict the information that is displayed dependent on the users previous selections.

This has taken me about an hour to type up. Hopefully it makes sense, I am still fairly new to iOS development and Objective C, and this concept is really pushing my capabilities and before I move on and end up hasing some crap together that I will have to fix later on I am hoping that one or some of you will be able to lend your experience in this type of this to me so I can get this right first time :)

If you need me to clarify anything or provide you more information that will help you help me just let me know.

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The common pattern for passing information backwards in your view controller hierarchy is to use delegation. You can achieve this in your scenario by implementing the following:

1) Define a protocol in the SearchParametersViewController, which represents your the parent view controller you mentioned.

@protocol SearchParametersViewControllerDelegate <NSObject>
@optional
- (void)searchOptionsSelected:(NSArray *)selectedSearchOptions;
@end

2) Conform to that protocol in your SearchOptionsSelectionViewController, which represents the table view controller that has a list of selections to choose from. Make sure to import or forward-declare the class the protocol is defined in (e.g. SearchParametersViewController) .

#import "SearchParametersViewController.h"

@interface SearchOptionsSelectionViewController <SearchParametersViewControllerDelegate>

3) Define a delegate property in your SearchOptionsSelectionViewController (assumes you are using ARC on iOS 5.0, 4.x use unsafe_unretained instead of weak. Use assign if the project is using manual memory management). This delegate object will contain a reference to your parent view controller (e.g. SearchParametersViewController). You do not want this property to be retained as to avoid retain cycles/circular references where one object references another, which in turn has a reference back to the first and neither object is ever deallocated.

@property (nonatomic, weak) id<SearchParametersViewControllerDelegate> delegate;

4) When instantiating the SearchOptionsSelectionViewController instance inside your parent view controller (SearchParametersViewController), set the delegate property to the parent view controller instance as represented by the self keyword. This ensures you can send the message (and corresponding data) backward in your view controller hierarchy, yet the object relationships remain loosely coupled. This delegate protocol could be conformed to in any other view controller, there are no tight relationships in the selection view controller back to the parent view controller, the only thing linking them is the flexible delegate protocol adoption by the selection view controller.

SearchOptionsSelectionViewController *selectionViewController = [[SearchOptionsSelectionViewController alloc] init];
selectionViewController.delegate = self;

5) Finally, in your SearchOptionsSelectionViewController table view's -tableView:didSelectRowAtIndexPath: delegate method, pass the data corresponding to the selected row back to your parent view controller (SearchParametersViewController) via the delegate method you defined in the SearchParametersViewControllerDelegate protocol. You must use the -respondsToSelector: method to ensure that the delegate object actually implements the -searchOptionsSelected: delegate method. To force this implementation, change @optional to @required above the method prototype in the protocol definition in step #1. self.someDataArray represents a the data source you are using with the selection table view controller. The specifics of the delegate protocol method and data object(s) sent back to the parent view controller can be changed, the important thing here is the delegation pattern and not having any tightly coupled relationships between the instances of either class, but especially backwards in the view controller hierarchy.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.delegate respondsToSelector:@selector(searchOptionsSelected:)])
    {
        NSArray *selectedObjs = [NSArray arrayWithObject:[self.someDataArray objectAtIndex:indexPath.row]];
        [self.delegate searchOptionsSelected:selectedObjs]
    }
}

6) Implement the delegate method inside SearchOptionsSelectionViewController.m

- (void)searchOptionsSelected:(NSArray *)selectedSearchOptions
{
    // do what you need to with selectedSearchOptions array
}

Further reading:

Cocoa Fundamentals Guide - Delegates and Data Sources

Cocoa Core Competencies - Protocol


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...