PlacesViewController.m 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. ////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2014 Realm Inc.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. //
  17. ////////////////////////////////////////////////////////////////////////////
  18. #import "PlacesViewController.h"
  19. #import "Place.h"
  20. @interface PlacesViewController () <UITextFieldDelegate>
  21. @property (nonatomic, weak) IBOutlet UITextField *searchField;
  22. @property (nonatomic) RLMResults *results;
  23. @end
  24. @implementation PlacesViewController
  25. - (void)viewDidLoad {
  26. [super viewDidLoad];
  27. RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
  28. config.readOnly = YES;
  29. config.fileURL = [[NSBundle mainBundle] URLForResource:@"Places" withExtension:@"realm"];
  30. [RLMRealmConfiguration setDefaultConfiguration:config];
  31. [self reloadData];
  32. }
  33. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  34. return self.results.count;
  35. }
  36. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  37. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
  38. Place *place = self.results[indexPath.row];
  39. cell.textLabel.text = place.postalCode;
  40. if (place.county) {
  41. cell.detailTextLabel.text = [NSString stringWithFormat:@"%@, %@, %@", place.placeName, place.state, place.county];
  42. } else {
  43. cell.detailTextLabel.text = [NSString stringWithFormat:@"%@, %@", place.placeName, place.state];
  44. }
  45. return cell;
  46. }
  47. - (void)reloadData {
  48. self.results = [Place allObjects];
  49. if (self.searchField.text.length > 0) {
  50. self.results = [self.results objectsWhere:@"postalCode beginswith %@", self.searchField.text];
  51. }
  52. self.results = [self.results sortedResultsUsingKeyPath:@"postalCode" ascending:YES];
  53. [self.tableView reloadData];
  54. }
  55. - (void)textFieldDidEndEditing:(UITextField *)textField {
  56. [self reloadData];
  57. }
  58. @end