2014-11-12 3 views
0

저녁,선택한 행을 상세보기로 전달

세부보기를 구성하는 중입니다. 데이터는 plist 파일에 저장되며 각 항목에는 단어와 정의가 있습니다. 테이블 뷰의 셀에는 단어가 레이블로 지정됩니다. 단어와 정의를 모두 보여주는 세부보기로 이어지는 각 단어를 찾고 있습니다. 코드가 잘못된 단어를 표시하고 있습니다. 나는 tableview.m에 단어와 정의를 설정하려고 시도하고 이것을 사용하여 세부 사항보기에서 레이블을 설정합니다. 내 검색어가 잘못된 단어가 표시되는 이유와 그 단어와 일치하는 올바른 정의를 얻을 수있는 이유입니다.

내 코드는 다음과 같습니다. 감사합니다. 사전은 본질적으로 순서가 있기 때문에

#import "RCViewController.h" 
#import "detailViewController.h" 

@interface RCViewController() 

@end 

@implementation RCViewController 

static NSString *CellIdentifier = @"Cell Identifier"; 

@synthesize words; 
@synthesize alphabetizedWords; 
@synthesize wordDictionary; 


-(NSDictionary *)alphabetizedWords:(NSArray *)wordsArray { 
    NSMutableDictionary *buffer = [[NSMutableDictionary alloc]init]; 

    for (int i=0; i <words.count; i++) { 
     NSString *word = [words objectAtIndex:i]; 
     NSString *firstLetter = [[word substringToIndex:1]uppercaseString]; 

     if ([buffer objectForKey:firstLetter]) { 
      [(NSMutableArray *)[buffer objectForKey:firstLetter]addObject:word]; 
     } 
     else { 
      NSMutableArray *mutableArray = [[NSMutableArray alloc]initWithObjects:word, nil]; 
      [buffer setObject:mutableArray forKey:firstLetter]; 
     } 
    } 
    NSArray *keys = [buffer allKeys]; 
    for (int j; j<keys.count; j++) { 
     NSString *key = [keys objectAtIndex:j]; 
     [(NSMutableArray *)[buffer objectForKey:key]sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; 
    } 
    NSDictionary *result = [NSDictionary dictionaryWithDictionary:buffer]; 
    return result; 
} 

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    NSArray *keys = [self.alphabetizedWords allKeys]; 
    return [keys count]; 
} 

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    NSArray *unsortedKeys = [self.alphabetizedWords allKeys]; 
    NSArray *sortedKeys = [unsortedKeys sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; 
    NSString *key = [sortedKeys objectAtIndex:section]; 
    NSArray *wordsForSection = [self.alphabetizedWords objectForKey:key]; 
    return [wordsForSection count]; 
} 

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 


    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 


    NSArray *unsortedKeys = [self.alphabetizedWords allKeys]; 
    NSArray *sortedKeys = [unsortedKeys sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; 
    NSString *key = [sortedKeys objectAtIndex:[indexPath section]]; 
    NSArray *wordsForSection = [self.alphabetizedWords objectForKey:key]; 
    NSString *word = [wordsForSection objectAtIndex:[indexPath row]]; 

    [cell.textLabel setText:word]; 

    return cell; 
} 

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    NSArray *keys = [[self.alphabetizedWords allKeys]sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; 
    NSString *key = [keys objectAtIndex:section]; 
    return key; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

    // perform the segue by getting the cell selected and passing it to the prepareForSegue method 
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 
    [self performSegueWithIdentifier:@"showDetail" sender:cell]; 
} 

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ 
    if ([segue.identifier isEqualToString:@"showDetail"]) { 
     NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow]; 


     detailViewController *destViewController = segue.destinationViewController; 
     destViewController.word = [words objectAtIndex:indexPath.row]; 

    } 
} 



- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

    NSString *path = [[NSBundle mainBundle]pathForResource:@"words" ofType:@"plist"]; 
    NSArray *wordsDictionary = [NSArray arrayWithContentsOfFile:path]; 

    self.words = [wordsDictionary valueForKey:@"Word"]; 

    self.alphabetizedWords = [self alphabetizedWords:self.words]; 

    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:CellIdentifier]; 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

@end 


#import <UIKit/UIKit.h> 

@interface detailViewController : UIViewController 


@property (weak, nonatomic) IBOutlet UILabel *wordLabel; 
@property (nonatomic, strong) NSString *word; 
@property (weak, nonatomic) IBOutlet UILabel *definitionLabel; 
@property (strong, nonatomic)NSString *definition; 

@end 


#import "detailViewController.h" 

@interface detailViewController() 

@end 

@implementation detailViewController 

@synthesize word; 
@synthesize wordLabel; 
@synthesize definition; 
@synthesize definitionLabel; 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     // Custom initialization 
    } 
    return self; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view. 

    wordLabel.text = word; 
    definitionLabel.text = definition; 

} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

/* 
#pragma mark - Navigation 

// In a storyboard-based application, you will often want to do a little preparation before navigation 
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    // Get the new view controller using [segue destinationViewController]. 
    // Pass the selected object to the new view controller. 
} 
*/ 

@end 
+0

갭! ** cellForRowAtIndexPath에서 매번 자신의 키 목록을 정렬하지 마십시오! 아주 나쁜 아이디어. 단어 목록이 30 단어 이상이되면 성능이 저하됩니다. 테이블 뷰를 표시 할 준비가되면 테이블 뷰 데이터 항목 (단어)의 배열을 작성한 다음 cellForRowAtIndexPath 및 prepareForSegue에서 사전 작성된 배열을 사용하십시오. –

+0

그 머리를 주셔서 감사합니다 - 내가 찾은 튜토리얼에서 왔지만 조언 해 주셔서 감사합니다. 이 문제를 해결하기 위해 속성으로 생성하고 연결된 값을 설정 한 다음 메서드에서 참조하기 만하면된다는 생각에 맞습니까? – user3692490

+0

예. 항목의 정렬 된 배열을 한 번 빌드하고 속성에 저장 한 다음 필요할 때마다 사용하십시오. –

답변

0

당신은 alphabetizedWords라는 사전을 갖는

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ 
    if ([segue.identifier isEqualToString:@"showDetail"]) { 
     NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow]; 
     detailViewController *destViewController = segue.destinationViewController; 

     NSArray *unsortedKeys = [self.alphabetizedWords allKeys]; 
     NSArray *sortedKeys = [unsortedKeys sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; 
     NSString *key = [sortedKeys objectAtIndex:[indexPath section]]; 
     NSArray *wordsForSection = [self.alphabetizedWords objectForKey:key]; 
     NSString *word = [wordsForSection objectAtIndex:[indexPath row]]; 
     destViewController.word = word; 

    } 
} 
+0

감사합니다. 마지막 것; 그 단어를 올바른 정의와 일치시키는 것이 최선의 방법입니다. 나는 objectatindex를 시도했다 : [self.tableview indexpathforselectedrow] .row] valueforkey : @ "Definition"]; 대상보기 컨트롤러 정의를 설정하지만 잘못된 정의가 표시됩니다. – user3692490

+0

@ user3692490, 귀하의 데이터 구조가 무엇인지 모르겠으므로 알려 드릴 수 없습니다. 나는 당신이 단어를 얻으려고했던 것과 비슷한 것을해야 할 것이라고 생각합니다. – rdelmar

0

, 당신이 cellForRowAtIndexPath에서 사용하는 워드를 얻을 수 prepareForSegue에서 같은 논리를 사용하기 위해 필요한 것은 꽤 의미가있다. 배열에서 데이터 구조를 설정해야합니다. 아마도 각 사전에 하나의 키에 단어가 있고 다른 키에 정의가 들어있는 사전 배열이 필요합니다. 배열을 정렬하고 테이블 뷰 데이터 소스에 피드를 사용하고 탭에 응답하여 정보를 상세보기 컨트롤러에 전달할 수 있습니다.

관련 문제