2015-05-07 2 views
0

ok новый объектив c. У меня есть приложение, которое собирается на веб-сайт и вытаскивает данные компании. Адрес компании и т. Д. Я хочу отображать состояние от каждой компании. Но мне нужно только одно из каждого показанного состояния. Например, если у меня есть CA, CA, CA, AZ, AZ, AZ, NY. Я только хочу отображать на моем столе CA, AZ, NY. Я пробовал differentUnionOfObjects, но я думаю, что использую его неправильно. любая помощь?удалить дубликаты из массива объектов

#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 
+0

Я пробовал NSordered комплект. Но я получаю эту ошибку. Элемент инициализатора не является константой времени компиляции. Должен ли он быть добавлен до того, как я вернусь из массива компании или когда-нибудь? – cmdace

ответ

1

Предположим, у вас есть Company объект со следующим интерфейсом:

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

Далее, допустим, вы делаете следующее:

// 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 массив & uniqueStatesSet набор оба содержат два объекта, @"CA" и @"AZ" (два способа получения уникальных заданных объектов) ,

+0

Его вытаскивающие данные компании с веб-сайта url. Поэтому мне не нужно знать, как добавлять компании. Как фильтровать существующий массив. – cmdace

+0

Я включил эти строки, чтобы вы поняли, что я инициировал массив объектов Компании. Просто пропустите эту часть и воспользуйтесь остальными. – Rufel

+0

Я получаю эту ошибку: использование незаявленного идентификатора «я». любые идеи – cmdace

1
NSArray *companies = …; 

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

Если у вас есть упорядоченный список уникальных предметов, вы должны использовать упорядоченный набор для его моделирования.

+0

ok Я попробовал вышеуказанное от Амина. Я вставил его после возвращения массивных компаний. Я получаю ошибку, этот элемент инициализатора не является константой времени компиляции – cmdace

+0

Можете ли вы показать точный код? –

+0

Точный код указан выше. Таким образом, верхняя часть идет по URL-адресу и извлекает информацию о компании. Нижняя часть получает состояния и подталкивает их к представлению таблицы. Я не знаю, как или применять код, чтобы показывать только одно из каждого состояния. – cmdace

Смежные вопросы