阵列重复不起作用
Posted
技术标签:
【中文标题】阵列重复不起作用【英文标题】:Array reduplication not working 【发布时间】:2015-05-13 21:28:53 【问题描述】: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
【问题讨论】:
在您尝试获取 keyPath 之前,公司的数组结构是什么样的 我已经尝试过日志,但我没有得到任何输出。可能放错地方了。 我的过滤器只针对一个州我得到了这个..2015-05-13 15:30:04.232 公司列表[3574:100861] 数组:(CA)这是正确的。只有一个 CA。表格视图上没有显示任何内容 【参考方案1】:通过使用谓词和块来检查现有状态的集合,我能够获得唯一的状态列表。像这样:
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 数组如下所示:
[
"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"
]
【讨论】:
我得到一个 Xcode 错误..StatesTableViewController.m:81:17: 读取字典元素的预期方法在“NSMutableArray *”类型的对象上找不到 这可能是tableview控制器的问题吗? 你的代码 81 is[(NSArray *)companies[@"companies"] OK 代码现在没有错误。但是表格视图上仍然没有结果。 2015-05-13 16:46:10.895 公司列表[3978:116117] 独特状态:(“”,“”)以上是关于阵列重复不起作用的主要内容,如果未能解决你的问题,请参考以下文章
preferredStatusBarStyle 不起作用[重复]