типичный нераспознанный селектор UITableView, отправленный экземпляру

У меня эта ошибка "tableView:cellForRowAtIndexPath:]: нераспознанный селектор отправлен в экземпляр", я почти уверен, что это какая-то проблема с управлением памятью, но сейчас я очень устал от необходимости находить ошибку. TableView хорошо отображает ячейки, пока вы не прокручиваете вниз, если вы это сделаете... сбой приложения. Единственное свойство, которое я использую, называется «места», я уже проверил, не пропустил ли я «я».

так вот мой код:

#import "PlacesViewController.h"
#import "FlickrFetcher.h"
#import "SinglePlaceViewController.h"

@implementation PlacesViewController

@synthesize places;

- (NSArray *)places
{
    if (!places) {
        NSSortDescriptor *content = [[NSSortDescriptor alloc] initWithKey:@"_content" ascending:YES];
        NSArray *unsortedPlaces = [FlickrFetcher topPlaces];    
        places = [unsortedPlaces sortedArrayUsingDescriptors:[NSArray arrayWithObjects: content, nil]];
    }
    return places;
}

#pragma mark -
#pragma mark Initialization

#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Top Places";
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}


// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return YES;
}


#pragma mark -
#pragma mark Table view data source

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


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return self.places.count;
}

- (NSDictionary *)placeAtIndexPath:(NSIndexPath *)indexPath
{
    return [self.places objectAtIndex:indexPath.row];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"PlacesTableViewCell";
    NSLog(@"%@", [FlickrFetcher topPlaces]);
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell...
    NSString *location = [[self placeAtIndexPath:indexPath] objectForKey:@"_content"];
    NSArray *splitLocation = [location componentsSeparatedByString:@", "];
    cell.textLabel.text = [splitLocation objectAtIndex:0];
    if (splitLocation.count == 2)
        cell.detailTextLabel.text = [splitLocation objectAtIndex:1];
    if (splitLocation.count == 3)
        cell.detailTextLabel.text = [[[splitLocation objectAtIndex:1] stringByAppendingString:@","] stringByAppendingString:[splitLocation objectAtIndex:2]];

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
}


#pragma mark -
#pragma mark Table view delegate

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

    // Navigation logic may go here. Create and push another view controller.

    SinglePlaceViewController *spvc = [[SinglePlaceViewController alloc] init];
    // Pass the selected object to the new view controller.
    spvc.placeId = [[self placeAtIndexPath:indexPath] objectForKey:@"place_id"];
    [self.navigationController pushViewController:spvc animated:YES];
    [spvc release];

}


#pragma mark -
#pragma mark Memory management

- (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 {
    [places release];
    [super dealloc];
}


@end

Большое спасибо за вашу помощь, и мне очень жаль, что заставил вас всех, ребята, сделать немного работы для меня.


person pchang    schedule 05.05.2011    source источник
comment
Можете ли вы пропустить всю часть // Configure the cell... и прокрутить? Я знаю, что это не покажет текст, но не произойдет ли сбой? Пожалуйста, опубликуйте трассировку стека и полный вывод консоли.   -  person Nick Weaver    schedule 05.05.2011
comment
Какой класс унаследовал PlacesViewController? Вы должны просмотреть делегата вашего tableview   -  person Tony    schedule 29.05.2013
comment
Вы пытались установить точку останова исключения в своем проекте? Куда отправляется сообщение? Кто получатель?   -  person Jarsen    schedule 29.06.2013


Ответы (2)


Вы не предоставили много информации об ошибке, поэтому я могу только догадываться:

Ошибка указывает на то, что объект, который получает сообщение cellForRowAtIndexPath:, на самом деле не реализует этот метод. Но поскольку вы ДЕЙСТВИТЕЛЬНО реализовали его, единственная причина, о которой я могу думать, заключается в том, что вы возитесь со свойством «dataSource» вашего tableView и меняете его на то, что вам не следует.

Убедитесь, что источником данных является ваш PlacecViewController.

person Avi Shukron    schedule 05.05.2011

Как мне кажется, метод получения для вашего свойства places не сохраняет возвращаемое им значение. Вы устанавливаете его на автоматически выпущенный экземпляр NSArray, который вы получаете из метода sortedArray. Я готов поспорить, что он будет выпущен после того, как отобразит ваши начальные ячейки таблицы.

person phoenixeyes    schedule 16.03.2012