如何在NSUser默认值中保存按钮选择

时间:2017-01-16 03:49:45

标签: ios objective-c nsuserdefaults

*

//
    //  DetailTableViewController.m
    //  BeautifulWorld
    //
    //  Created by Mahesh on 10/27/15.
    //  Copyright © 2015 Mahesh. All rights reserved.
    //
    #import "DetailTableViewController.h"
    #import "DetailTableViewCell.h"
    #import "ContentViewController.h"
    #import "TableViewHeader.h"
    @import UIKit;
    @interface DetailTableViewController ()
    @end
    @implementation DetailTableViewController{
        NSMutableArray* selectedPlaces;
        NSDictionary* place;
        NSArray* places;
    }
    DetailTableViewCell * detailcell ;
    - (void)viewDidLoad {
        [super viewDidLoad];
        selectedPlaces = [[NSMutableArray alloc]init];
        
        selectedItems = [[NSMutableArray alloc] init];
        
        
        //TODO:- NSUserDefaults Attempt
        
        selectedPlaces = [NSMutableArray arrayWithArray:(NSArray *)[[NSUserDefaults   standardUserDefaults] objectForKey:@"selectedPlaces"]];
        if(selectedPlaces == nil){
            selectedPlaces = [[NSMutableArray alloc] init];
        }else{
            NSLog(@"Saved to Defaults");
        
        }
        // Uncomment the following line to preserve selection between presentations.
        // self.clearsSelectionOnViewWillAppear = NO;
        
        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem;
        
        detailcell.loveImageView.highlighted = YES;
        
        self.navigationItem.title = _DetailTableModal[0];
        
    //Wonders Of The World
        //[[NSOperationQueue mainQueue] addOperationWithBlock:^ {
            
            //Your code goes in here
            //NSLog(@"Main Thread Code");
        
       
            if ([self.navigationItem.title isEqualToString:@"Wonders Of The World"])
            {
                
                
              NSArray*  titleArray = @[@"Pyramid at 'Chichen Itza'",
                          @"Christ the Redeemer",
                          @"Great Wall of China",
                          @"Machu Picchu",
                          @"Petra",
                          @"Taj Mahal",
                          @"Colosseum ",];
                
                Title = [titleArray mutableCopy];
                
                
               NSArray*   descriptionArray = @[@"Yucatan, Mexico",
                                @"Rio de Janeiro - RJ, Brazil",
                                @"China",
                                @"Peru",
                                @"Wadi Musa,Jordan",
                                @"Agra,Uttar Pradesh,India",
                                @"Rome,Italy",];
                
                Description = [descriptionArray mutableCopy];
                
                 NSArray*  imageArray = @[@"1ChichenItza.jpg",
                          @"2ChristtheRedeemer.jpg",
                          @"3GreatWallofChina.jpg",
                          @"4MachuPicchu.jpg",
                          @"5Petra.jpg",
                          @"6Tajmahal.jpg",
                          @"7Colosseum.jpg",];
                
                Image = [imageArray mutableCopy];
                
            }
        
        
       // }];
        
        
        if ([self.navigationItem.title isEqualToString:@"Sky Scrapers"])
        {
        
          NSArray*  titleArray = @[@"Burj Kalifa",
                  @"Eiffel Tower",
                  @"Empire State Building",
       
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    -(void)viewWillAppear:(BOOL)animated{
        
        [self myValue];
        self.tabBarController.tabBar.hidden = NO;
    }
    #pragma mark - Table view data source
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
        return 1;
    }
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        
        return Title.count;
    }
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        
        static NSString * CellIdentifier = @"DetailCell";
        
        detailcell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        
        int row = (int)[indexPath row];
        
        detailcell.DetailTableCellTitle.text = Title[row];
        detailcell.DetailTableCellDescription.text = Description[row];
        detailcell.DetailTableCellImageView.image= [UIImage imageNamed:Image[row]];
        
        if([selectedItems containsObject:indexPath]){
            //high
            detailcell.loveImageView.highlighted = YES;
        }else{
            //gray
            detailcell.loveImageView.highlighted = NO;
        }
        
        // Adding Tag To The Love Button
       // detailcell.loveImageView.tag = indexPath.row;
        detailcell.favouriteButton.tag = indexPath.row;
        
        // Adding Tap Guesture To Love Button
        detailcell.loveImageView.userInteractionEnabled = YES;
    //    UITapGestureRecognizer *tapGesture1 = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(loveImageTapped:)];
    //    tapGesture1.numberOfTapsRequired = 1;
    //    [detailcell.loveImageView addGestureRecognizer:tapGesture1];
        
        [detailcell.favouriteButton addTarget:self action:@selector(loveImageTapped:) forControlEvents:UIControlEventTouchUpInside];
        
        return  detailcell;
        
    }
    #pragma mark Delete Rows With Animation
    - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
    {
        [tableView beginUpdates];
        [Image removeObjectAtIndex:indexPath.row];
        [Description removeObjectAtIndex:indexPath.row];
        [Title removeObjectAtIndex:indexPath.row];
        
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
        [tableView endUpdates];
        NSIndexPath * rowToReload = [NSIndexPath indexPathForRow:indexPath.row inSection:0];
        NSArray * rowsToReload = [NSArray arrayWithObjects:rowToReload, nil];
        
        [tableView reloadRowsAtIndexPaths:rowsToReload withRowAnimation:UITableViewRowAnimationLeft];
       
   
        
    }
    #pragma mark Love Button Tapped
    -(void)loveImageTapped:(UIButton*)sender {
        sender.selected = !sender.selected; //calling your method
        [self saveMyValue:sender.selected];
        
        if (sender.selected) {
            [sender setBackgroundImage:[UIImage imageNamed:@"HeartSelectedSmall"] forState:UIControlStateNormal];
            [selectedPlaces addObject:selectedPlaces];
        }else{
            [sender setBackgroundImage:[UIImage imageNamed:@"Heart"] forState:UIControlStateNormal];
        }
        [self.tableView reloadData];
       
    } // Your Methods Added
    // Set the value
    - (void)saveMyValue:(BOOL)myValue {
        [[NSUserDefaults standardUserDefaults] setInteger:[NSNumber numberWithBool:myValue ].integerValue forKey:@"myActionKeyHere"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    } // Your Methods Added
    // Get the value
    - (NSInteger)myValue {
        NSInteger myValue = [[NSUserDefaults standardUserDefaults] integerForKey:@"myActionKeyHere"];
        return myValue ;
    }
    /*
    // Override to support conditional editing of the table view.
    - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
        // Return NO if you do not want the specified item to be editable.
        return YES;
    }
    */
    /*
    // Override to support editing the table view.
    - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            // Delete the row from the data source
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        } else if (editingStyle == UITableViewCellEditingStyleInsert) {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }   
    }
    */
    /*
    - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
    }
    */
    /*
    
    - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
        // Return NO if you do not want the item to be re-orderable.
        return YES;
    }
    */
    #pragma mark - Navigation To The Detail Content View.
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
       
        if ([[segue identifier] isEqualToString:@"ShowDetails"]) {
            ContentViewController * contentView = [ segue destinationViewController];
            
            NSIndexPath * myindexpath = [self.tableView indexPathForSelectedRow];
            
            int row = (int)[myindexpath row];
            contentView.ContentModal = @[Title[row],Description[row],Image[row]];
            
        }
    }
    @end Did The Same. Can you please explain me a bit more. What to do in cell for row at index path

*

3 个答案:

答案 0 :(得分:0)

如果它是一个BOOL,你可以保存它,如果你想要多个选项,只需更改为NSInteger:

//设置值

- (void)saveMyValue:(BOOL)myValue {
    [[NSUserDefaults standardUserDefaults] setInteger:[NSNumber numberWithBool:myValue ].integerValue forKey:@"myActionKeyHere"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

//获取值

- (NSInteger)myValue {
    NSInteger myValue = [[NSUserDefaults standardUserDefaults] integerForKey:@"myActionKeyHere"];
    return myValue ;
}

答案 1 :(得分:0)

@Hauzin告诉你NSUserDefaults的方式。

顺便说一句,我对你的案子有另一个想法。

首先,按钮选择状态的类型是BOOL类型。 所以我们必须将BOOL值设置为NSNumber值。 ([NSNumber numberWithBool:xxx])

然后,如果你有一个UITableView并且UITableView需要多个按钮的选择状态,你可以将按钮选择状态保存为NSArray。 然后你可以编写一个带有NSArray类型参数的方法来创建新的UITableView。 (例如: - (void)setupXXXtableViewWithButtonStatus:(NSArray *)buttonStatusArray;)

答案 2 :(得分:0)

如果要在NSUserDefault中保存按钮状态,可以使用以下代码。

NSUserDefaults *udefaults=[NSUserDefaults standardUserDefaults];
if (btn.selected) {
    [udefaults setBool:YES forKey:@"isSelected"];
}else{
    [udefaults setBool:NO forKey:@"isSelected"];
}

要获得可以使用的按钮状态。

NSUserDefaults *udefaults=[NSUserDefaults standardUserDefaults];

BOOL isButtonSelected = [udefaults boolForKey:@"isSelected"]; 

另外,请勿忘记在此synchronize上致电udefaults

[udefaults synchronize];

希望,这有帮助。