Удаление основных данных единой записи через таблицу iPhone - PullRequest
0 голосов
/ 23 января 2012

Использование основных данных для заполнения моего табличного представления.Чего я не понимаю, так это как я могу удалить одну запись из основных данных.

Вот код, который я использую:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

if (tableView == favouritesTable) {
    cellValue = [licensePlateArray objectAtIndex:indexPath.row];
} else { // handle search results table view
    cellValue = [filteredListItems objectAtIndex:indexPath.row];
}

static NSString *CellIdentifier = @"vlCell";

VehicleListCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

    NSLog(@"Cell Created");

    NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"VehicleListCell" owner:nil options:nil];

    for (id currentObject in nibObjects) {
        if ([currentObject isKindOfClass:[VehicleListCell class]]) {
            cell = (VehicleListCell *)currentObject;
        }
    }

    UILongPressGestureRecognizer *pressRecongnizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(tableCellPressed:)];
    pressRecongnizer.minimumPressDuration = 0.5f;
    [cell addGestureRecognizer:pressRecongnizer];
    [pressRecongnizer release];
}

cell.textLabel.font = [UIFont systemFontOfSize:10];

Favouritesdata *favdata = [licensePlateArray objectAtIndex:indexPath.row];

[[cell ignition] setImage:[UIImage imageNamed:@"ignition.png"]];
[[cell direction] setImage:[UIImage imageNamed:@"south.png"]];

cell.licPlate.text = [favdata licenseplate];

NSLog(@"cellvalue for cellforRow: %@", cell.licPlate.text);

return cell;}

В методе UILongPressGestureRecognizer:

- (void)tableCellPressed:(UILongPressGestureRecognizer *)recognizer{

if (recognizer.state != UIGestureRecognizerStateBegan) {
    return;
}

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles: nil] ;

[alert addButtonWithTitle:@"Remove from Favourites"];
[alert addButtonWithTitle:@"Take to Map"];

[alert show];}

В методе просмотра предупреждений:

-(void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex {

NSString *title = [alert buttonTitleAtIndex:buttonIndex];

NSManagedObjectContext *contextFav = [app managedObjectContext];
Favouritesdata * favourites = [NSEntityDescription insertNewObjectForEntityForName:@"Favouritesdata" inManagedObjectContext:contextFav];

if([title isEqualToString:@"Remove from Favourites"])
{
    NSLog(@"cellValueForLongPress: %@", cellValueForLongPress);


    if (cellValueForLongPress <= 0) {

        NSLog(@"No data to delete");

    }
    else {

        favourites.licenseplate = cellValueForLongPress;
    }

    [alert dismissWithClickedButtonIndex:0 animated:YES];
}
else if([title isEqualToString:@"Take to Map"])
{
    NSLog(@"Go to MapView");
}

NSError *error;

if (![context save:&error]) {
    NSLog(@"Error Occured");
}}

Ответы [ 2 ]

1 голос
/ 23 января 2012

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

  1. Ссылка на NSManagedObjectContext, из которой вы будете удалять объект: context
  2. Ссылка на NSManagedObject, которую вы хотите удалить: object

Тогда удалить объект будет очень просто:

[context deleteObject:object];

Вы должны знать

  1. индекс строки для удаления, например, i.
  2. получить его из вашего массива: NSObject *object = [licensePlateArray objectAtIndex:i];
  3. удалить его из db: [context deleteObject: object];
  4. удалить его из массива: [licensePlateArray removeObject: object];
0 голосов
/ 23 января 2012

Вы должны идентифицировать свой NSManagedObject и затем вызвать deleteObject для вашего управляемогоObjectContext.Затем этот объект будет удален из ваших основных данных.

Но вы должны предоставить механизм, чтобы «как-то» получить объект за определенной строкой табличного представления.

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