2013-06-26 3 views
0

У меня возникла проблема с заполнением таблицы в следующем сегменте. В основном я отправляю все строки в одну комбинированную строку, а затем заполняю массив. Из этого массива я заполняю таблицу. Проблема в том, что это проявляется только в самой первой ячейке. Я бы хотел, чтобы каждая запись имела запятую для перехода к следующей ячейке. Вот код для первого ViewControler.hНаполнение таблицы из массива появляется только на первой ячейке

@interface ViewController : UIViewController { 

IBOutlet UITableView  *myTableView; 
NSMutableArray *locationArray; 

} 


@property (nonatomic, retain) IBOutlet UITableView  *myTableView; 
@property (nonatomic, retain)   NSMutableArray *locationArray; 

- (void) populateLocationArray; 
@end 

Вот ViewController.m

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
[tableView deselectRowAtIndexPath:indexPath animated:YES]; 
NSLog(@"Row Selected %i",indexPath.row); 



if (indexPath.section==0) { 

    [self performSegueWithIdentifier:@"first" sender:nil]; 

} 

} 

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ 
NSLog(@"PrepareForSegueCalled"); 
LocationItems *destination = [segue destinationViewController]; 

//If statement for city pressed 
destination.titleOfView = @"Boston"; 

NSArray *myStrings = [[NSArray alloc] initWithObjects:@"first", @"second", @"third", @"fourth", @"fifth", nil]; 
destination.arrayToBePopulatedString = [myStrings componentsJoinedByString:@" "]; 
// destination.arrayToBePopulatedString = [myStrings componentsJoinedByString:@"|"]; 
    // [destination.populationArray addObjectsFromArray:myStrings]; 
} 

Контроллер называется LocationItems это вид с таблицей, я хотел бы заполнить. Вот LocationItems.h

@interface LocationItems : UIViewController 
{ 
IBOutlet UITableView  *locationTableView; 
NSString *titleOfView; 
NSString *arrayToBePopulatedString; 
NSMutableArray *populationArray; 

NSMutableArray *bostonArray; 
} 

- (void) populateArray; 

@property (nonatomic, retain) IBOutlet UITableView *locationTableView; 
@property (strong, nonatomic) NSString *titleOfView; 
@property (strong, nonatomic) NSString *arrayToBePopulatedString; 
@property (strong, nonatomic) NSMutableArray *populationArray; 
@property (nonatomic, retain) NSMutableArray *bostonArray; 

@end 

И, наконец, LocationItems.m

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 
bostonArray = [[NSMutableArray alloc] init]; 
[self populateArray]; 


//******************************************************** 
//If string = boston load some array containing the cities. 

// Do any additional setup after loading the view from its nib. 
} 

- (void) populateArray { 

[bostonArray addObject:arrayToBePopulatedString]; 
//[bostonArray addObject:populationArray]; 
//[bostonArray addObject:@"Boston"]; 
} 

// 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:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 

    [[cell textLabel] setNumberOfLines:1]; 
    //[[cell textLabel] setLineBreakMode: 

    } 

// Configure the cell. 
[cell.textLabel setText:[bostonArray objectAtIndex:indexPath.row]]; 
return cell; 
} 

// 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 [bostonArray.self count]; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
[tableView deselectRowAtIndexPath:indexPath animated:YES]; 
NSLog(@"Row Selected %i",indexPath.row); 




} 

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

Спасибо!

+0

Как выглядит ваш массивToBePopulatedString? Использовать NSLog в ViewDidLoad в LocationItems.m – davis

+0

Это используется в методе populateArray. [bostonArray addObject: arrayToBePopulatedString]; – Tanner

ответ

1

Я не уверен, что я понимаю, что вы имеете в виду:

Я посылаю все строки в одной объединенной строки, то заселение в массив с ним.

Вы хотите разбить строку, содержащую все подстроки, и сделать массив из него?

Из того, что я получаю от вашего кода, вы берете сцепленную строку, где все значения разделены пробелами и хранить его в качестве первого элемента массива:

destination.arrayToBePopulatedString = [myStrings componentsJoinedByString:@" "]; 
... 
[bostonArray addObject:arrayToBePopulatedString]; 

Это просто добавляет полную строку в массиве.

Если вы хотите разделить сцепленную строку обратно в массив, вероятно, вы должны использовать что-то вроде

bostonArray = [[destination.arrayToBePopulatedString componentsSeparatedByString: @" "] retain]; 

Тогда вам больше не нужно выделять массив в вашем viewDidLoad.

+0

Здравствуйте, это все еще оставляет все слова в первой ячейке. – Tanner

+0

Здравствуйте, извините за предыдущий комментарий. У меня был код в неправильном месте. Это сработало. Спасибо огромное! – Tanner

+0

Рад, что это помогло. Я только заметил, что мне не хватает сохранения, поскольку componentsSeparatedByString возвращает объект с автореализацией.bostonArray становится плохой ссылкой, как только он автореализован, что приведет к случайным сбоям при попытке получить к нему доступ. Я обновил ответ, чтобы исправить это. –

0
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [bostonArray.self count]; // typo here? [self.bostonArray count] 
} 
+0

Спасибо, что поймали это. – Tanner

0

Самое простое решение заключается в изменении bostonArray addObject в bostonArray addObjectsFromArray.

Использование addObject приводит к добавлению всего массива к первому элементу bostonArray.

+0

В его случае arrayToBePopulatedString является NSString. Он преобразовал исходный массив в один NSString, поэтому он добавляет всю строку в качестве первого элемента пустого массива. –

+0

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