2012-02-19 3 views
0

У меня есть стек Core Data, в котором есть два объекта: «Клиент» и «Автомобиль». Оба они представлены tableViewControllers.Ошибка на контроллерах viewed coredata

Первый tableViewController выбирает список клиентов, а затем один раз выбран, второй отображает список автомобилей , которыми владеет клиент. Оба нажимаются на контроллер навигации. Когда я вернусь из второго диспетчера представлений, программа успешно проверит первый контроллер управления, ждет секунду или вот-вот сработает. Когда я сделал «сборку и отладку», консоль выдала эту ошибку:

Program received signal: “EXC_BAD_ACCESS”. 

Я не понимаю. Где я должен искать ошибку?

EDIT: Я добавил код ниже, чтобы узнать, связано ли это с неправильной обработкой памяти ... Я удалил все закомментированные методы, а также те, которые не использовались до появления ошибок.

Это мой ClientListViewController ...

@implementation ClientListViewController 

@synthesize clientsArray; 
@synthesize coreDataModel; 

#pragma mark - 
#pragma mark View lifecycle 


- (void)viewDidLoad { 
    [super viewDidLoad]; 

    // Set the title 
    [email protected]"Clients"; 

    [self populateTable]; 
} 

-(void)populateTable { 

    [self setClientsArray:[coreDataModel retrieveClientList]]; 

} 


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { 
    // Override to allow orientations other than the default portrait orientation. 
    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 [clientsArray 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... 

    Client *client = (Client *)[clientsArray objectAtIndex:indexPath.row]; 
    cell.textLabel.text = [client name]; 

    return cell; 

    [client release]; 


#pragma mark - 
#pragma mark Table view delegate 

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

    // Create and push new view controller. 
    ClientCarsViewController *clientCarsViewController = [[ClientCarsViewController alloc] initWithNibName:@"ClientCarsViewController" bundle:nil]; 

    //Pass the CoreDataModel to the view controller 
    clientCarsViewController.coreDataModel = coreDataModel; 

    // Pass the selected object to the new view controller 
    Client *client = (Client *)[clientsArray objectAtIndex:indexPath.row]; 
    clientCarsViewController.client = client; 

    // Push the new viewController 
    [self.navigationController pushViewController:clientCarsViewController animated:YES]; 

    // Release the objects 
    [clientCarsViewController release]; 
    [client 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. 
    self.clientsArray = nil; 
} 


- (void)dealloc { 

    [clientsArray release]; 
    [coreDataModel release]; 
    [super dealloc]; 

} 


@end 

Это моя реализация ClientCarsViewController ...

@implementation ClientCarsViewController 

@synthesize carsArray; 
@synthesize coreDataModel; 
@synthesize client; 


#pragma mark - 
#pragma mark View lifecycle 


- (void)viewDidLoad { 
    [super viewDidLoad]; 

    self.title = client.name; 

    // Get client's cars 
    NSSet *cars = client.cars; 

    // Import them into the carsArray 
    [self setCarsArray: [NSMutableArray arrayWithArray:[cars allObjects]]]; 

    [cars release]; 

} 

-(void)addCarToClient { 

    [coreDataModel addCarToClient:(Client *)client]; 

} 


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { 
    // Override to allow orientations other than the default portrait orientation. 
    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 [carsArray 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... 
    Car *car = (Car *)[carsArray objectAtIndex:indexPath.row]; 
    cell.textLabel.text = [car carName]; 
    return cell; 

    [car release]; 

} 


#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. 

} 


#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. 
    self.carsArray = nil; 
} 


- (void)dealloc { 

    [self.client release]; 
    [self.coreDataModel release]; 
    [self.carsArray release]; 
    [super dealloc]; 
} 


@end 
+0

Ошибка обычно означает, что вы пытаетесь получить доступ к тому, что не выделено или которое было освобождено. Что вы в этой секунде, после чего приложение выйдет из строя? У вас нет дополнительной информации об ошибке: строка, где это происходит, и т. Д.? – sch

+0

Я ничего не делаю, я нажимаю «назад», подождите секунду или около того, затем он падает и дает мне эту ошибку. Нет дополнительной информации. Я могу только предположить, что я выпустил объект, который я не должен был иметь к этому моменту. Я редактирую свой пост и вставляю код, чтобы узнать, помогает ли это ... –

+0

Для таких ошибок вы можете включить переменную среды NSZombieEnabled. Это поможет вам определить, какой выпущенный объект вы пытаетесь достичь. – aslisabanci

ответ

1

Вы освобождаетесь объекты, которые вы не владеете. Посмотрите на Objective-C Memory Management Rules.

Например, когда вы получаете объект client, как это:

Client *client = (Client *)[clientsArray objectAtIndex:indexPath.row]; 

Вы не владеете его и не отпускал его.

+0

ahhh ... ok. Спасибо –

+0

Я удалил 3 экземпляра выпуска, как вы предложили. 2 в первом контроллере представления и 1 во втором. Во время выполнения я могу теперь выбрать клиента и успешно вернуться. Я могу выбрать другого клиента. Однако, как только я нажимаю на клиенте во второй раз, я получаю ту же ошибку и сбой. Есть ли еще одна ошибка? –

+0

нашел окончательную ошибку - я также выпускал NSSet, но не обладал им! Еще раз спасибо. –

Смежные вопросы