0

ok new to objective c. I have my app going to a web site and pulling company data. Company name address etc. I want to display the state from each company. But I only want one of each state shown. For example if I have CA,CA,CA,AZ,AZ,AZ,NY. I only want to display on my tableview CA,AZ,NY. I am have tried distinctUnionOfObjects, but I think I am using it wrong. any help?

#import "StatesTableViewController.h"

@interface StatesTableViewController ()

@end

@implementation StatesTableViewController

NSArray *companies;


- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *address = @"http://www.Feed";
    NSURL *url = [[NSURL alloc] initWithString:address];

    //laod the data on a background queue..
    //if we were connecting to a an online url then we need it
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        companies = [self readCompanies:url];

        //now that we have the data, reload the table data on the main ui thread
        [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
    });
}


//new code
- (NSArray *)readCompanies:(NSURL *)url {
    //create a nsurlrequest with the given Url
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:
                             NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30.0];

    //get the data
    NSURLResponse *response;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

    //now create a nsdictionary from the json data
    NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data
                                                                   options:0 error:nil];

    //create a new array to hold the comanies
    NSMutableArray *companies = [[NSMutableArray alloc] init];

    //get an array of dictionaries with the key "company"
    NSArray *array = [jsonDictionary objectForKey:@"companies"];

    //iterate throught the array of dictionaries
    for (NSDictionary *dict in array) {
        //create a new company object with information in the dictionary
        Company *company = [[Company alloc] initWithJSONDictionary:dict];

        //add the Company object to the array
        [companies addObject:company];


    }


    //return the array of Company objects
    return companies;







}
//trying to get 1 state here?  should i create a new array?
//added code to show 1 of each state.   companies array now uniquevalues
//NSArray* uniqueValues = [companies valueForKeyPath:[NSString stringWithFormat:@"distinctUnionOfObjects.%@",@"state"]];

//or
//static NSArray *uniqueValues = nil;
//if (uniqueValues == nil){
//    uniqueValues = [NSArray arrayWithArray:[companies valueForKeyPath:[NSString stringWithFormat:@"distinctUnionOfObjects.%@",@"state"]]];
//}
//or

//companies = [companies valueForKeyPath:@"@distinctUnionOfObjects.state"];

//end added code



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark -table view controller methods
//change uniqueValue errors to companies

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger) section {
  //    return [uniqueValues count];
    return [companies count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *cellID = @"CellIDState";
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellID];

    if (cell == nil){
        //single line on table view
        //cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
        // dual line on table view
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
    }

     //Company *company = [uniqueValues objectAtIndex:indexPath.row];
    Company *company = [companies objectAtIndex:indexPath.row];

    //cell.textLabel.text = company.company_id;
    cell.textLabel.text = company.state;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",company.companyName];
    //adds cheveron to tableviewl
    [cell setAccessoryType: UITableViewCellAccessoryDisclosureIndicator];

    return cell;
}

#pragma mark - navigation
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{


}


@end
1
  • I have tried NSordered set. But I get this error. Initializer element is not a compile-time constant. Should it be added before I return the company array or sometime after? Commented May 7, 2015 at 18:46

2 Answers 2

2

Suppose you have a Company object with the following interface:

@interface Company : NSObject
@property (nonatomic) NSString *name;
@property (nonatomic) NSString *state;
@end

Next, let's say you do the following:

// Creating & adding a few companies
Company *company1 = [Company new];
company1.name = @"Some Company";
company1.state = @"CA";

Company *company2 = [Company new];
company2.name = @"Some Company";
company2.state = @"CA";

Company *company3 = [Company new];
company3.name = @"Some Company";
company3.state = @"CA";

Company *company4 = [Company new];
company4.name = @"Some Company";
company4.state = @"AZ";

Company *company5 = [Company new];
company5.name = @"Some Company";
company5.state = @"AZ";

self.companies = @[company1, company2, company3, company4, company5];

NSArray *uniqueStates = [self.companies valueForKeyPath:@"@distinctUnionOfObjects.state"];
NSSet *uniqueStatesSet = [NSSet setWithArray:[self.companies valueForKey:@"state"]];

The uniqueStates array & uniqueStatesSet set will both contain two objects, @"CA" and @"AZ" (two ways of getting a unique set objects).

Sign up to request clarification or add additional context in comments.

4 Comments

Its pulling company data from a web site url. So i don't need to know how to add companies. Just how to filter the existing array.
I included those lines only so you'd understand that I was instanciating an array of Company objects. Just skip that part and make use of the rest.
I get this error: Use of undeclared identifier 'self'. any ideas
So Far No answers. All Attempts have failed. Anybody have any ideas???
1
NSArray *companies = …;

NSOrderedSet *states = [NSOrderedSet orderedSetWithArray:[companies valueForKey:@"state"]];

If you have an ordered list of unique items, you should use an ordered set to model it.

3 Comments

ok I tried the above from Amin. I inserted it after the return of the array companies. I get a error this Initializer element is not a compile-time constant
Can you show the exact code?
The exact code is above. So the top part is going to the url and pulling the information of the company. The bottom part is getting the states and pushing it to the table view. I don't know how or were to apply the code to only show one of each state.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.