数组重复无法正常工作

时间:2015-05-13 21:28:53

标签: objective-c arrays json uitableview

Xcode问题。我有一个nsmutablearray拉json对象。示例公司:姓名,州,地址,电话号码等

我正在提取信息。我想在表格视图中显示每个州的1个。它工作正常,但显示相同状态的多个。但我只想展示每个州的1个。我正在使用一些代码,但它不会返回任何状态。我已经看到了很多例子,这应该可行,但它什么都不返回。如果我跳过下面的代码,它会显示所有状态。我也试过一个for循环。并尝试了阵列到NSSet。什么都行不通。有任何想法吗??? 我的问题是这个代码......

    //Create states only array...remove duplicate states here
NSArray *statesArray = [companies valueForKeyPath:@"@distinctUnionOfObjects.state"];

return statesArray;

这是我的整个代码。请帮忙解决这个问题一个星期。

@interface StatesTableViewController ()

@property (nonatomic) NSString *name;
@property (nonatomic) NSString *state;

@end

@implementation StatesTableViewController

NSArray *companies;
NSArray *statesArray;

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *address = @"http://www.companiesFeed";
    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];//, statesSet = [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 ];

    }


    //Create states only array...remove duplicate states here
    NSArray *statesArray = [companies valueForKeyPath:@"@distinctUnionOfObjects.state"];

    return statesArray;
     //return companies;
}

- (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[companies count];
    return [statesArray 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];
    }

    //edit single state
    //Company *company = [companies objectAtIndex:indexPath.row];
    Company *company = [statesArray 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 个答案:

答案 0 :(得分:0)

通过使用谓词和块来检查现有状态的集合,我能够获得唯一的状态列表。像这样:

NSMutableArray *statesArray = [NSMutableArray array];
    [companies filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        Company *dict = (Company *)evaluatedObject;
        BOOL seen = [statesArray containsObject:dict];
        if (!seen) {
            [statesArray addObject:dict];
        }
        return !seen;
    }]];
    NSLog(@"unique states:  %@", statesArray);

公司阵列看起来像这样:

{[{
  "company_id": "22",
  "entityformSubmissionID": "22",
  "companyName": "house of waffles",
  "companySlogan": " where your home is!",
  "address1": "123 here",
  "address2": "thre",
  "city": "everywhere",
  "state": "CA",
  "zipCode": "94531",
  "phoneNumber": "777-777-7777",
  "email": "test@test.com",
  "additionalCompanyInfo": "all additional company info is going here",
  "sales": "There are no sales!",
  "rentalTerms": "Terms is dont break our stuff jerks!",
  "companyLogo": "/16x16icon.png"
}]