How to save NSMutablearray in NSUserDefaults

前端 未结 9 1178
盖世英雄少女心
盖世英雄少女心 2020-11-29 17:50

I have two NSMutableArray\'s. They consist of images or text. The arrays are displayed via a UITableView. When I kill the app the data within the <

9条回答
  •  心在旅途
    2020-11-29 18:09

    Note: NSUserDefaults will always return an immutable version of the object you pass in.

    To store the information:

    // Get the standardUserDefaults object, store your UITableView data array against a key, synchronize the defaults
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:arrayOfImage forKey:@"tableViewDataImage"];
    [userDefaults setObject:arrayOfText forKey:@"tableViewDataText"];
    [userDefaults synchronize];
    

    To retrieve the information:

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSArray *arrayOfImages = [userDefaults objectForKey:@"tableViewDataImage"];
    NSArray *arrayOfText = [userDefaults objectForKey:@"tableViewDataText"];
    // Use 'yourArray' to repopulate your UITableView
    

    On first load, check whether the result that comes back from NSUserDefaults is nil, if it is, you need to create your data, otherwise load the data from NSUserDefaults and your UITableView will maintain state.

    Update

    In Swift-3, the following approach can be used:

    let userDefaults = UserDefaults.standard
    
    userDefaults.set(arrayOfImage, forKey:"tableViewDataImage")
    userDefaults.set(arrayOfText, forKey:"tableViewDataText")
    userDefaults.synchronize()
    
    var arrayOfImages = userDefaults.object(forKey: "tableViewDataImage")
    var arrayOfText = userDefaults.object(forKey: "tableViewDataText")
    

提交回复
热议问题