2012-04-09 1 views
1

ОК, я действительно искал темы, которые, кажется, покрывают это, но до сих пор не нашли того, что работает для меня. Этот список создается путем отправки каждой загрузки страницы UIWebView. В какой-то момент, если пользователь хочет очистить этот список, у меня есть кнопка, которая отображает предупреждение, которое просто подтверждает, что они хотят очистить, а затем нажмите OK, чтобы очистить. Пожалуйста, расскажи мне, как я могу это сделать. Примерно на полпути вы можете найти мою clearAllData, которая является кнопкой clearAllRecents, но моя функция void под ней является моей?Удалить или очистить ВСЕ объекты данных в UITableView с помощью кнопки предупреждения?

#import "RecentViewController.h" 
#import "ViewController.h" 

@interface RecentViewController() 

@end 

@implementation RecentViewController 

@synthesize recent, explorerView; 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     // Custom initialization 
    } 
    return self; 
} 

- (void)viewDidLoad 
{ 
    recent = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"Recent"] mutableCopy]; 
    [super viewDidLoad]; 
} 

- (void)viewDidUnload 
{ 
    [super viewDidUnload]; 
} 

- (IBAction)cancelButtonTapped 
{ 
    [self setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal]; 
    [self.presentingViewController dismissModalViewControllerAnimated:true]; 
} 

- (IBAction)clearAllRecents 
{ 
    UIAlertView *alert = [[UIAlertView alloc] 
         initWithTitle:@"clear all recents?" 
         message:@"press ok to clear" 
         delegate: self 
         cancelButtonTitle:@"cancel" 
         otherButtonTitles:@"ok", nil]; 
    [alert show]; 
} 

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex 
{ 
    if (buttonIndex == 1) { 
     //clear all recent objects?????????????????????????????????????????????? 
    } 
} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [recent count]; 
} 

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyle)UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; 
    } 

    cell.textLabel.text = [recent objectAtIndex:(recent.count - indexPath.row - 1)]; 
    cell.textLabel.textColor = [UIColor whiteColor];; 
    cell.textLabel.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:20.0]; 
    return cell; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    explorerView.urlField.text = [recent objectAtIndex:(recent.count - indexPath.row - 1)]; 
    [explorerView textFieldShouldReturn:explorerView.urlField]; 
    [self.presentingViewController dismissModalViewControllerAnimated:true]; 
    explorerView = nil; 
    recent = nil; 
    tableView = nil; 
} 

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (editingStyle == UITableViewCellEditingStyleDelete) { 
     [recent removeObjectAtIndex:indexPath.row]; 
     [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationFade]; 
     [[NSUserDefaults standardUserDefaults] setObject:recent forKey:@"Recent"]; 
    } 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    return (interfaceOrientation == UIInterfaceOrientationPortrait); 
} 

@end 

ответ

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

if (buttonIndex == 1) { 
    [recent removeAllObjects]; 
    [[NSUserDefaults standardUserDefaults] setObject:recent forKey:@"Recent"]; 
    [yourTableView reloadData]; 
}} 

Это должно сделать это.

+0

Я пробовал это, и проблема, которую я получаю, это [yourTableView reloadData]; для меня неправильный тэгТайпВеп. Я попробовал UITableView и reloadData неизвестно. Просто tableView вызывает ошибки и предлагает использовать UITableView. – user1264599

+0

Я не упомянул, что это было uitableview в UIViewController. Итак, я исправил неизвестный метод, добавив @property (неатомный, сохраняющий) IBOutlet UITableView * myTableView; к моему .h и подключению его в IB. Итак, теперь таблица очищается, но как только я возвращаюсь в таблицу, она снова заполняется всеми данными. Что мне не хватает? – user1264599

+0

Ваша проблема: '- (void) viewDidLoad { Недавнее = [[[[NSUserDefaults standardUserDefaults] arrayForKey: @" Недавние "] mutableCopy]; [super viewDidLoad]; } ' Каждый раз, когда загружается представление,' recent' присваивается значения из ваших пользовательских значений по умолчанию. Если вы хотите удалить значения навсегда, вам нужно будет сбросить «arrayForKey: @» Недавние ». В противном случае вам нужно будет найти другой способ загрузить значения - возможно, предоставив пользователю возможность перезагрузить ретентатов. (См. Отредактированный ответ) – AMayes