Не удалось вызвать указанный инициализатор в классе NSManagedObject - PullRequest
4 голосов
/ 19 июля 2011

Еще один вопрос новичка, как раз тогда, когда я думал, что начинаю очень мало понимать программирование на ios.Тьфу!Я следую учебному пособию на appcodeblog.com, где создаю простое приложение на панели вкладок, использующее основные данные для ввода, отображения и поиска мест назначения для отпуска.Я работал над учебником и у меня есть работающее приложение, но я замечаю, что при выборе вкладки «Показать места назначения» я получаю следующую ошибку.Приложение продолжает работать, но ошибка регистрируется на консоли.Я пытаюсь решить проблему и точно понять, что происходит, но я просто не совсем понимаю, что не так.Я "думаю", что у меня есть проблема с моим файлом ShowDestination.xib, где я неправильно подключил свои объекты в XIB.Буду признателен за любую оказанную помощь.Заранее спасибо за помощь и время.

Вот ошибка: «CoreDataTabBarTutorial [1262: 207] Не удалось вызвать назначенный инициализатор для класса NSManagedObject 'Destination'.

Я не уверен, чтокод для предоставления, поэтому я начал с показа моих заголовочных файлов и файлов реализации ShowDistinationViewController.h и ShowDestitionsViewController.m

ShowDistinationViewController.h

#import <UIKit/UIKit.h>


@interface SearchDestinationsViewController : UIViewController {

    UISearchBar *destinationSearchBar;
    UITableView *searchTableView;

    NSFetchedResultsController *fetchedResultsController;
    NSManagedObjectContext *managedObjectContext;

    NSArray *fetchedObjects;

 }

@property (nonatomic, retain) IBOutlet UISearchBar *destinationSearchBar;
@property (nonatomic, retain) IBOutlet UITableView *searchTableView;

@property (nonatomic, retain) IBOutlet NSFetchedResultsController *fetchedResultsController;
@property (nonatomic, retain) IBOutlet NSManagedObjectContext *managedObjectContext;

@end

ShowDestitionsViewController.m

#import "ShowDestinationsViewController.h"
#import "Destination.h"

@implementation ShowDestinationsViewController

@synthesize destinationsTableView;
@synthesize destinationsArray;
@synthesize fetchedResultsController;
@synthesize managedObjectContext;

// Not sure where the following code came from so I commented it out!!! It didn't seem to break anything when I commented it out
//- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
//{
//    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
//    if (self) {
//        // Custom initialization
//    }
//    return self;
//}

- (void)dealloc
{
    [destinationsArray release];
    [destinationsTableView release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a      nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
}
*/

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark -
#pragma Data Fetch from Core Data

- (void) viewWillAppear:(BOOL)animated
{

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Destination" inManagedObjectContext:managedObjectContext];
    [request setEntity:entity];
    NSError *error = nil;
    NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    if (mutableFetchResults == nil)
    {
        // Handle the error.
        NSLog(@"mutableFetchResults == nil");
    }
    [self setDestinationsArray:mutableFetchResults];
    [request release];
    [destinationsTableView reloadData];
} 


#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 [destinationsArray count];
}

// 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] autorelease];
    }

    // Configure the cell...
    Destination *destination = [[Destination alloc] init];
    destination = (Destination *)[destinationsArray objectAtIndex:indexPath.row];
    cell.textLabel.text = destination.name;
    [destination release];

    return cell;
}

#pragma mark -
#pragma mark Table view delegate

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

}

@end

1 Ответ

6 голосов
/ 19 июля 2011

Проблема, похоже, заключается в

Destination *destination = [[Destination alloc] init];
destination = (Destination *)[destinationsArray objectAtIndex:indexPath.row];
[destination release];

Первая строка не нужна: в Objective-C Destination* - это указатель на объект, а не на реальный объект.Нужный объект Destination предположительно уже находится в массиве.Таким образом, вам не нужно создавать объект для указания в строке [[Destination alloc] init], который сразу же исчезает на следующей строке.

  1. [[Destination alloc] init] создает объект a, destination указывает на a.a хранится у вас.
  2. (Destination *)[destinationsArray objectAtIndex:indexPath.row] дает вам еще один объект b, который не удерживается вами.destination теперь указывает на b.Никто больше не удерживает a.
  3. release отправляется объекту, на который указывает destination, т. Е. На b.Это против правила удержания-выпуска;вы должны выпустить a, а не b!

Так что вместо этого просто сделайте

Destination *destination = (Destination *)[destinationsArray objectAtIndex:indexPath.row];

без release part.

Asсовет: всегда запускайте Analyze (который доступен под меню Build) при сборке проекта.Анализатор предназначен для выявления распространенных типов ошибок, в том числе ваших.Исправьте ваш код так, чтобы все предупреждения анализатора исчезли;вы всегда должны рассматривать предупреждение анализатора как ошибку с вашей стороны.

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