Подклассы с CoreData и UITableviewController - PullRequest
1 голос
/ 12 июля 2011

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

По сути, у меня есть весь код в суперклассе, исключаемый для FetchedResultController, который я переопределяю в своих подклассах.без этого «split», но теперь он возвращает сообщение EXC_BAD_ACCESS.

Вот код в моем подклассе:

    - (NSFetchedResultsController *)fetchedResultsController
    {
        if (super.fetchedResultsController != nil)
        {
            return super.fetchedResultsController;
        }
        id delegate = [[UIApplication sharedApplication] delegate];

        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Question" inManagedObjectContext:[delegate managedObjectContext]];
        [fetchRequest setEntity:entity];

        [fetchRequest setFetchBatchSize:20];

        NSSortDescriptor*sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"up_vote_count" ascending:YES];
        NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
        [fetchRequest setSortDescriptors:sortDescriptors];

        //next line returns EXC_BAD_ACCESS
        NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[delegate managedObjectContext] sectionNameKeyPath:nil cacheName:@"Root2"];
        aFetchedResultsController.delegate = self;
        super.fetchedResultsController = aFetchedResultsController;

        NSError *error = nil;
        if (![self.fetchedResultsController performFetch:&error])
        {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }

        return super.fetchedResultsController;
    }   

Мне любопытно, стоит ли использовать super. или self. но self. в операторе if произошел сбой.

- EDIT -

Вот @ -интерфейс интерфейсасуперкласс.Мой подкласс не содержит ничего, кроме перезаписанных методов.

@interface CoreDataTableView : UITableViewController <NSFetchedResultsControllerDelegate> {  


 }

 - (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;

 @property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;
 @property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
 @end

1 Ответ

2 голосов
/ 13 июля 2011

сам.произошел сбой в операторе if

Это связано с тем, что вы рекурсивно вызываете метод fetchedResultsController в бесконечный цикл.

Теперь есть еще несколько проблем.

Во-первых, я бы предложил разделить этот метод на 2 части:

  1. инициализация контроллера извлеченных результатов
  2. выборка данных

Кроме того, вашfetchRequest никогда не выпускается.И не aFetchedResultsController.Вы владеете обоими этими объектами внутри этого метода, поэтому вы должны освободить их для предотвращения утечек.

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

- (NSFetchedResultsController *)fetchedResultsController
{
    // In this method, because it's overriding the accessor in the super-class,
    // you must use |super.fetchedResultsController|, 
    // otherwise you will trigger an infinite loop!

    if (super.fetchedResultsController != nil)
    {
        return super.fetchedResultsController;
    }
    id delegate = [[UIApplication sharedApplication] delegate];

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // ...

    // omitted the other details...       

    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[delegate managedObjectContext] sectionNameKeyPath:nil cacheName:@"Root2"];
    aFetchedResultsController.delegate = self;
    super.fetchedResultsController = aFetchedResultsController;

    [aFetchedResultsController release];
    [fetchRequest release];

    return super.fetchedResultsController;
}


- (void)fetch
{
    NSError *error = nil;
    // using |self| here is OK, because you're referring to the current object's method
    if (![self.fetchedResultsController performFetch:&error])
    {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }        
} 

Что касается использования super против self:

  • super.foo или [super foo] начинает искать метод foo в суперклассе
  • self.foo или [self foo]для метода foo в классе текущего объекта

В вашем случае это не будет иметь большого значения, за исключением того факта, что self.fetchedResultsController вызовет бесконечный цикл, как я упоминал ранее, если он используетсявнутри аксессора.

Надеюсь, я понял это правильно и что это прояснило для вас ...

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