Сбой после возврата к просмотру таблицы - PullRequest
0 голосов
/ 09 декабря 2011

Итак, я пишу приложение для чтения RSS-канала и отображения содержимого в виде таблицы. Это также позволяет пользователю воспроизводить mp3-файлы, которые он находит для каждого элемента. В любом случае, до того, как я начал добавлять новые представления, приложение работало нормально. Теперь каждый раз, когда я возвращаюсь из вида и немного прокручиваю, я получаю «Программа получила сигнал« SIGABRT »» или что-то подобное.

вот большая часть программы:

- (IBAction)playAction:(id)sender
{
// Get row
UIButton *senderButton = (UIButton *)sender;
UITableViewCell *buttonCell = 
(UITableViewCell *) [[senderButton superview] superview];
NSInteger buttonRow = [[self.tableView 
                        indexPathForCell:buttonCell] row];

// Entry for row
RSSEntry *senderEntry = [_allEntries objectAtIndex:buttonRow];


// This is where _allEntries gets filled

- (void)requestFinished:(ASIHTTPRequest *)request {

[_queue addOperationWithBlock:^{

    NSError *error;
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[request responseData]
                                                           options:0 error:&error];

    if (doc == nil) 
    {
        NSLog(@"Failed to parse %@", request.url);
    } 
    else 
    {

        NSMutableArray *entries = [NSMutableArray array];
        [self parseRss:doc.rootElement entries:entries]; 

        if ([_allEntries count] > 0) {

            [[NSOperationQueue mainQueue] addOperationWithBlock:^{

                // Update
                int i=0;
                while (![[[_allEntries objectAtIndex:i] articleUrl] isEqualToString:[[entries objectAtIndex:i] articleUrl]]) 
                {
                    [_allEntries insertObject:[entries objectAtIndex:i] atIndex:0];
                    i++;
                }
                [self.tableView reloadData];
            }];

        }
        else
        {
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{

                for (RSSEntry *entry in entries)
                {
                    [_allEntries addObject:entry];
                }

                NSLog(@"entries:%d", [_allEntries count]);
                [self.tableView reloadData];
            }];
        }


    }

}];



}
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"View did load");

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] 
                                          initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh 
                                          target:self 
                                          action:@selector(refreshButton:)];

pauseImage = [UIImage imageNamed:@"pause_circle_small.png"];
playImage = [UIImage imageNamed:@"play_circle_small.png"];

player = nil;
isPlaying = NO;

self.title = @"Feed";
self.allEntries = [NSMutableArray array];
self.queue = [[[NSOperationQueue alloc] init] autorelease];
self.feed = [[NSString alloc] initWithString:@"http://site.org/rss/"];
[self refresh];
}


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

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

UILabel *mainLabel, *secondLabel;
UIButton *playBtn;

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

    mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(42.0, 5.0, 250.0, 20.0)] autorelease];
    mainLabel.tag = MAINLABEL_TAG;
    mainLabel.font = [UIFont fontWithName:@"Arial-BoldMT" size:18.0];
    mainLabel.textAlignment = UITextAlignmentLeft;
    mainLabel.textColor = [UIColor blackColor];
    mainLabel.highlightedTextColor = [UIColor whiteColor];
    [cell.contentView addSubview:mainLabel];

    secondLabel = [[[UILabel alloc] initWithFrame:CGRectMake(42.0, 27.0, 250.0, 15.0)] autorelease];
    secondLabel.tag = SECONDLABEL_TAG;
    secondLabel.font = [UIFont fontWithName:@"ArialMT" size:14.0];
    secondLabel.textAlignment = UITextAlignmentLeft;
    secondLabel.textColor = [UIColor colorWithRed:222.0/255.0 green:95.0/255.0 
                                             blue:199.0/255.0 alpha:1.0];
    secondLabel.highlightedTextColor = [UIColor whiteColor];
    [cell.contentView addSubview:secondLabel];

    playBtn = [UIButton buttonWithType:UIButtonTypeCustom];

    playBtn.tag = PLAYBTN_TAG;
    playBtn.frame = CGRectMake(2.0, 6.0, playImage.size.width, playImage.size.height);
    [playBtn setBackgroundImage:playImage forState:UIControlStateNormal];
    //[playBtn setBackgroundImage:playImage forState:UIControlStateHighlighted];

    [playBtn addTarget:self action:@selector(playTapped:) 
      forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:playBtn];
}
else 
{
    mainLabel = (UILabel *)[cell.contentView viewWithTag:MAINLABEL_TAG];
    secondLabel = (UILabel *)[cell.contentView viewWithTag:SECONDLABEL_TAG];
    playBtn = (UIButton *)[cell.contentView viewWithTag:PLAYBTN_TAG];
}

// Alternate bg color
if (indexPath.row%2 == 0) {
    UIColor *altColor = [UIColor colorWithRed:230.0/255.0 green:230.0/255.0
                                         blue:230.0/255.0 alpha:1];
    mainLabel.backgroundColor = altColor;
    secondLabel.backgroundColor = altColor;
}
else
{
    UIColor *altColor = [UIColor colorWithRed:255.0 green:255.0
                                         blue:255.0 alpha:1];
    mainLabel.backgroundColor = altColor;
    secondLabel.backgroundColor = altColor;
}

RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
NSLog(@"Entry: %@", entry);

// Manage play button
if (entry == currEntry)
{
    if(isPlaying)
    {
        [playBtn setBackgroundImage:pauseImage forState:UIControlStateNormal];
    }
    else
    {
        [playBtn  setBackgroundImage:playImage forState:UIControlStateNormal];
    }
}
else
    [playBtn setBackgroundImage:playImage forState:UIControlStateNormal];

mainLabel.text = entry.articleTitle;
secondLabel.text = entry.articleArtist;

return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.

DetailView *detailViewController = [[DetailView alloc] initWithNibName:@"DetailedView" bundle:[NSBundle mainBundle]];

RSSEntry *entry = [_allEntries objectAtIndex:[indexPath row]];



[self.navigationController pushViewController:detailViewController animated:YES];

detailViewController.songTitle.text = entry.articleTitle;
detailViewController.artistName.text = entry.articleArtist;

[entry release];

[detailViewController release];

}

- (void)dealloc
{
[player release];
player = nil;
[_queue release];
_queue = nil;
[_feed release];
_feed = nil;
[_allEntries release];
_allEntries = nil;

[super dealloc];
}

@end

Ответы [ 5 ]

1 голос
/ 09 декабря 2011

ахи !!!Я установил свой RSSEntry на автоматический выпуск, прежде чем помещать их в массив _allEntries.Они получали dealloc'd, когда я менял взгляды.Не делай этого.Спасибо всем за помощь.Это было так просто, теперь я чувствую себя глупо.

1 голос
/ 09 декабря 2011

Пожалуйста, не выпускайте переменную @synthesize. Вы должны только выпустить это в методе dealloc

1 голос
/ 09 декабря 2011

Это дикое предположение, но вы не сохраняете изображения, которые вы получаете в viewDidLoad:

pauseImage = [UIImage imageNamed:@"pause_circle_small.png"];
playImage = [UIImage imageNamed:@"play_circle_small.png"];

Либо используйте свойство сохранения и синтаксис с точками, либо отправьте каждое из них retain.

0 голосов
/ 09 декабря 2011

пожалуйста, не освобождайте self.feed, а также когда выгрузите или освободите представление в то время, поместите делегат nil означает

tableview.delegate = nil;

это основнойПосле этой вещи я думаю, что вы не обнуляете делегата tableview.

0 голосов
/ 09 декабря 2011

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

скорее всего, здесь

self.feed = [[NSString alloc] initWithString:@"http://site.org/rss/music"];
[self.feed release];

вы отпускаете объекты сразу, но трудно сказать, не зная, сохранили ли вы свойство

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