2012-06-15 2 views
0

что код сортированные этот словарь:отсортирован мой NSMutableDictionary

{ 
     "a) Saudi Arabia" =  (
      "2012/06/04 Huge Sandstorm", 
      "2011/03/30 Huge Sandstorm" 
     ); 
     "b) Niger" =  (
      "2012/05/27 Huge Sandstorm" 
     ); 
     "c) ****** QUATRE" =  (
      "2011/03/30 7Huge Sandstorm over niger", 
      "2011/03/30 8Huge Sandstorm over niger", 
     ); 
    } 

для моего UITableView?

с этим кодом мои названия заголовка секции в порядке, но не содержание:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{ 
    NSArray *allKeys = [[states allKeys] sortedArrayUsingSelector:@selector(compare:)]; 
    return [allKeys objectAtIndex:section]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell";  
    UITableViewCell *cell = (UITableViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

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

    NSArray *allKeys = [states allKeys] ; 
    NSString *curKey = [allKeys objectAtIndex:indexPath.section]; 
    NSArray *curArray = [states objectForKey:curKey]; 
    curValue = [curArray objectAtIndex:indexPath.row]; 

    cell.textLabel.text = curValue; 
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
    [[cell textLabel] setFont:[UIFont systemFontOfSize:12.0]]; 
    return cell; 
} 

Кто-то может помочь мне?

ответ

1

// использовать этот код

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return [[states allKeys] count];//returns the number of key/object pairs 
} 

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{ 
     NSArray *allKeys = [[states allKeys] sortedArrayUsingSelector:@selector(compare:)]; 
     return [allKeys objectAtIndex:section]; 
    } 

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
    { 
     NSArray *allKeys = [[states allKeys] sortedArrayUsingSelector:@selector(compare:)]; 
     NSString *curKey = [allKeys objectAtIndex:section]; 
     NSArray *curArray = [states objectForKey:curKey]; 

     return [curArray count]; 
    } 

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
      static NSString *CellIdentifier = @"Cell"; 

      UITableViewCell *cell = (UITableViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 

    } 
    // Configure the cell... 

    //---------- CELL BACKGROUND IMAGE ----------------------------- 
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:cell.frame]; 
    UIImage *image = [UIImage imageNamed:@"LightGrey.png"]; 
    imageView.image = image; 
    cell.backgroundView = imageView; 
    [[cell textLabel] setBackgroundColor:[UIColor clearColor]]; 
     [[cell detailTextLabel] setBackgroundColor:[UIColor clearColor]]; 


    NSArray *allKeys = [[states allKeys] sortedArrayUsingSelector:@selector(compare:)]; 

    NSString *curKey = [allKeys objectAtIndex:indexPath.section]; 
    NSArray *curArray = [[states objectForKey:curKey]  sortedArrayUsingSelector:@selector(compare:)]; 
    NSString *[email protected]""; 
    if([curArray count]>indexPath.row) 
     curValue = [curArray objectAtIndex:indexPath.row]; 

    if(curValue) 
     cell.textLabel.text = curValue; 

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 

    [[cell textLabel] setFont:[UIFont systemFontOfSize:12.0]]; 
    return cell; 

} 

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ 

    return 60; 

    } 

может быть, это поможет вам

+0

еще раз спасибо !!! – kratosphere

0

Вы сортируете ваш словарь в titleForHeaderInSection, но не в cellForRowAtIndexPath.

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

0

Это может быть полезно здесь. Если у вас есть сомнения, сообщите мне. Напишите этот код перед вызовом tableview.

NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:@"birthDate" ascending:YES selector:@selector(compare:)]; //pass the key of your dictionary here 
[allKeys sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]]; 
0

Вам нужно будет сортировать curKey

NSArray *curArray = [states objectForKey:curKey]; 
//Add this line after currArray 
NSArray *sorterCurArray = [curArray sortedArrayUsingSelector:@selector(compare:)]; 
//Use sorterCurArray instead 
curValue = [sorterCurArray objectAtIndex:indexPath.row]; 
+0

этот код ничего не меняет в порядке содержания – kratosphere

0
write the same code in your cellForRowAtIndexPath: too for accessing key 

NSArray *allKeys = [[states allKeys] sortedArrayUsingSelector:@selector(compare:)]; 
+0

У меня авария с тем, что я уже пробовал = S – kratosphere

+0

вы можете показать свой журнал сбоев ...? и почему он разбился, когда вы использовали эту строку в функции titleForHeaderInSection:. – Abhishek

+0

2012-06-15 15: 32: 44.649 StoryboardTutorial [2601: f803] *** Завершение приложения из-за неперехваченного исключения «NSRangeException», причина: '- [__ NSCFArray objectAtIndex:]: index (2) за пределами границ (2)' *** Первый стек бросить вызов: (0x13cc022 0x155dcd6 0x1374a48 0x13749b9 0x13c5c30 0x2ed6 0xb0c54 0xb13ce 0x9ccbd 0xab6f1 0x54d42 0x13cde42 0x1d84679 0x1d8e579 0x1d134f7 0x1d153f6 0x1da2160 0x14e84 0x15767 0x24183 0x24c38 0x18634 0x12b6ef5 0x13a0195 0x1304ff2 0x13038da 0x1302d84 0x1302c9b 0x14c65 0x16626 0x237d 0x22e5) Terminate называется бросать исключение (lldb) – kratosphere

0
// 
// ViewController.m 
// StoryboardTutorial 
// 
// Created by Kurry Tran on 10/20/11. 
// Copyright (c) 2011 __MyCompanyName__. All rights reserved. 
// 

#import "ViewController.h" 
#import "DetailViewController.h" 
@implementation ViewController 
@synthesize states,datasource,curValue,sortedArray,descriptor; 
- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Release any cached data, images, etc that aren't in use. 
} 

#pragma mark - View lifecycle 

- (void)viewDidLoad 
{ 
    [self setupArray]; 
    [super viewDidLoad]; 

    // Do any additional setup after loading the view, typically from a nib. 
} 

-(void)setupArray{ 

    NSURL *myUrl=[NSURL URLWithString:@"the link with the dictionary"]; 
    // NSString *str = [NSString stringWithContentsOfURL:myUrl usedEncoding:nil error:nil]; //load above string here 
    NSMutableDictionary *dict=[NSMutableDictionary dictionaryWithContentsOfURL:myUrl]; 

// NSString *str [email protected]"# 2012/20110930 Huge Sandstorm over niger# just for the test/20110330 AHuge Sandstorm over niger/20110330 BHuge Sandstorm over niger"; 

// NSArray * firstArry = [str componentsSeparatedByString:@"#"]; 
// NSMutableArray *secondArry = [[NSMutableArray alloc] init]; //Will hold the # titles 
// NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; //Will hold the strings related to # title 
// for(NSString *firstArryStr in firstArry) 
// { 
//  NSArray *tempArry = [firstArryStr componentsSeparatedByString:@"\n"]; 
//  NSMutableArray *titleStingsArry = [[NSMutableArray alloc] init]; 
//  for (int i=0; i< [tempArry count];i++) { 
//   if (i==0) { 
//    NSString *title = [tempArry objectAtIndex:i]; 
//    [secondArry addObject:title]; 
//    [dict setValue:titleStingsArry forKey:title]; 
//   } else { 
//    [titleStingsArry addObject:[tempArry objectAtIndex:i]]; 
//   } 
//  } 
    NSLog(@"%@",dict); 

// }  

// NSString *myString = @"20110330 AHuge Sandstorm over niger/20110330 BHuge Sandstorm over niger/20110330 CHuge Sandstorm over niger/20110330 1Huge Sandstorm over niger/20110330 2Huge Sandstorm over niger/20110330 3Huge Sandstorm over niger/20110330 4Huge Sandstorm over niger/20110330 5CHuge Sandstorm over niger/20110330 6Huge Sandstorm over niger"; 
// NSArray *event = [myString componentsSeparatedByString:@"/"]; 
// states = [NSMutableArray arrayWithArray:event]; 

    self.states = [NSMutableDictionary dictionaryWithDictionary: dict]; 
datasource = [dict allKeys]; 

    self.navigationItem.title = @"test"; 



} 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return [states count];//returns the number of key/object pairs 
} 

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{ 
    NSArray *allKeys = [[states allKeys] sortedArrayUsingSelector:@selector(compare:)]; 

    return [allKeys objectAtIndex:section]; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    NSArray *allKeys = [states allKeys]; 
    NSString *curKey = [allKeys objectAtIndex:section]; 
    NSArray *curArray = [states objectForKey:curKey]; 

    return [curArray count]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = (UITableViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 

    } 
    // Configure the cell... 

    //---------- CELL BACKGROUND IMAGE ----------------------------- 
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:cell.frame]; 
    UIImage *image = [UIImage imageNamed:@"LightGrey.png"]; 
    imageView.image = image; 
    cell.backgroundView = imageView; 
    [[cell textLabel] setBackgroundColor:[UIColor clearColor]]; 
    [[cell detailTextLabel] setBackgroundColor:[UIColor clearColor]]; 


    NSArray *allKeys = [[states allKeys] sortedArrayUsingSelector:@selector(compare:)]; 

    NSString *curKey = [allKeys objectAtIndex:indexPath.section]; 
    NSArray *curArray = [states objectForKey:curKey]; 

    if([curArray count]>indexPath.row) curValue = [curArray objectAtIndex:indexPath.row]; 


    cell.textLabel.text = curValue; 

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 

    [[cell textLabel] setFont:[UIFont systemFontOfSize:12.0]]; 
    return cell; 

} 

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 
    NSArray *allKeys = [states allKeys]; 
    NSString *curKey = [allKeys objectAtIndex:indexPath.section]; 
    NSArray *curArray = [states objectForKey:curKey]; 
    curValue = [curArray objectAtIndex:indexPath.row]; 

    DetailViewController *detail = [self.storyboard instantiateViewControllerWithIdentifier:@"detail"]; 
    // detail.state = [states objectAtIndex:indexPath.row]; 
    detail.state = curValue; 
    [self.navigationController pushViewController:detail animated:YES]; 

} 

//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
//{ 
// //normal cell acquisition code 
//  
// NSArray *allKeys = [states allKeys]; 
// NSString *curKey = [allKeys objectAtIndex:indexPath.section]; 
// NSArray *curArray = [states objectForKey:curKey]; 
// NSString *curValue = [curArray objectAtIndex:indexPath.row]; 
// //Do something with the string 
// 
//} 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ 

    return 60; 

} 

- (void)viewDidUnload 
{ 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
    // e.g. self.myOutlet = nil; 
} 

- (void)viewWillAppear:(BOOL)animated 
{ 
    [super viewWillAppear:animated]; 
} 

- (void)viewDidAppear:(BOOL)animated 
{ 
    [super viewDidAppear:animated]; 
} 

- (void)viewWillDisappear:(BOOL)animated 
{ 
    [super viewWillDisappear:animated]; 
} 

- (void)viewDidDisappear:(BOOL)animated 
{ 
    [super viewDidDisappear:animated]; 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    // Return YES for supported orientations 
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); 
} 

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