Сортировать uitableview в возрастающем прайс-листе - PullRequest
2 голосов
/ 16 февраля 2012

Мое приложение содержит два массива (т.е. productArray и priceArray) и передает значение одного массива в ячейку.textlabel.text и другие массивы на cell.detaillabel.text.It работает нормально. Теперь я хочу отсортировать uitableview в возрастающем прайс-листе.подскажите пожалуйста как это сделать .. вот мой код ..

 #import <UIKit/UIKit.h>

@interface RootViewController : UITableViewController {
NSMutableArray *productArray;
NSMutableArray *priceArray;

}

@property(nonatomic,retain)NSMutableArray *productArray;
@property(nonatomic,retain)NSMutableArray *priceArray;
@end



 #import "RootViewController.h"



 @implementation RootViewController
 @synthesize productArray,priceArray;


 - (void)viewDidLoad {
   [super viewDidLoad];

    productArray=[[NSMutableArray alloc]initWithObjects:@"Apple",@"iphone",@"ipod",@"ipad",nil];
priceArray=[[NSMutableArray alloc]initWithObjects:@"4000",@"2000",@"100",@"1000",nil];

// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
 }


 #pragma mark -
 #pragma mark Table view data source

  // Customize the number of sections in the table view.
 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return 1;
}


 // Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section       {
  return [productsArray count];
}


  // Customize the appearance of table view cells.
  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:     (NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}

// Configure the cell.
cell.textLabel.text=[productsArray objectAtIndex:indexPath.row];
cell.detailTextLabel.text=[priceArray objectAtIndex:indexPath.row];

return cell;
}

 - (void)didReceiveMemoryWarning {
  // Releases the view if it doesn't have a superview.
  [super didReceiveMemoryWarning];

// Relinquish ownership any cached data, images, etc that aren't in use.
 }

- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}


- (void)dealloc {
  [super dealloc];
 }


 @end

1 Ответ

5 голосов
/ 16 февраля 2012

Считывание значений из двух разных массивов для заполнения ячейки табличного представления затрудняет сортировку.Я рекомендую вам создать один объект, который содержит атрибуты продукта и цены, а затем сохранить эти объекты в одном массиве.Затем вы можете просто отсортировать массив с помощью специального метода сортировки, который сравнивает цены.

Пример класса продукта:

@interface Product : NSObject
{
    NSString *productName;
    NSString *price;
}
@property (nonatomic, retain) NSString *productName;
@property (nonatomic, retain) NSString *price;

Затем напишите метод, который может сортировать товары по цене:

products = [products sortedArrayUsingSelector(sortByPrice:)];

... который вызывает этот метод в реализации ваших продуктов:

- (NSComparisonResult)sortByPrice:(id)anObject
{
    if (self.price < anObject.price) {
        return NSOrderedAscending;
    } else (if self.price > anObject.price) {
        return NSOrderedDescending;
    }
    return NSOrderedSame;
}

Хранить продукты в одном массиве:

NSMutableArray *products;

И ваши значения ячеек будут установлены какобъект из одного отсортированного массива.

Создание продукта изменяется с:

[products addObject:@"Milk"];
[prices addObject:@"2.25"];

на следующее:

Product *newProduct = [[[Product alloc] init] autorelease];
[products addObject:newProduct];
[newProduct setProductName:@"Milk"];
[newProduct setPrice:@"2.25"];

И установка значений в ячейках изменяется сэто:

cell.textLabel.text=[productArray objectAtIndex:indexPath.row];
cell.detailTextLabel.text=[priceArray objectAtIndex:indexPath.row];

до этого:

cell.textLabel.text=(Product *)[products objectAtIndex:indexPath.row].productName;
cell.detailTextLabel.text=(Product *)[products objectAtIndex:indexPath.row].price;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...