如何将JSON字符串保存到NSUserDefaults?

时间:2022-11-24 22:18:49

I have a JSON request which returns different parameters, name for example. I would like to cache a variable for the name parameter, which I can view in the app later.

我有一个JSON请求,返回不同的参数,例如名称。我想为name参数缓存一个变量,稍后我可以在app中查看。

For example: name from JSON request = david. the variable is called firstname. firstname should equal "david". firstname should be stored so I can view it in all parts of my apps.

例如:来自JSON request = david的名称。该变量称为firstname。 firstname应该等于“david”。应存储名字,以便我可以在我的应用程序的所有部分中查看它。

I saw another similar question were one solution was:

我看到另一个类似的问题是一个解决方案是:

NSString *valueToSave = @"someValue";
[[NSUserDefaults standardUserDefaults]
    setObject:valueToSave forKey:@"preferenceName"];

and to get it back later:

并在以后取回它:

NSString *savedValue = [[NSUserDefaults standardUserDefaults]
    stringForKey:@"preferenceName"];

How can I use this method when I'm parsing a JSON file like this?:

在解析像这样的JSON文件时,如何使用此方法?:

@implementation Videos

@synthesize tableView = _tableView, activityIndicatorView = _activityIndicatorView, movies = _movies;

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = @"Title";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Menu"
                                                                             style:UIBarButtonItemStylePlain
                                                                            target:(DEMONavigationController *)self.navigationController
                                                                            action:@selector(showMenu)];


    NSString *valueToSave = @"TitleString";
    [[NSUserDefaults standardUserDefaults]
     setObject:valueToSave forKey:@"title"];

    self.tableView.separatorColor = [UIColor clearColor];

    // Setting Up Activity Indicator View
    self.activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    self.activityIndicatorView.hidesWhenStopped = YES;
    self.activityIndicatorView.center = self.view.center;
    [self.view addSubview:self.activityIndicatorView];
    [self.activityIndicatorView startAnimating];
    self.tableView.separatorColor = [UIColor clearColor];

    // Initializing Data Source
    self.movies = [[NSArray alloc] init];

    NSURL *url = [[NSURL alloc] initWithString:@"http://link-to-json.php?name=Name"];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        self.movies = JSON;
        [self.activityIndicatorView stopAnimating];
        [self.tableView reloadData];

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
    }];

    [operation start];

}

// Table View Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.movies && self.movies.count) {
        return self.movies.count;
    } else {
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 374;
}

- (void)tableView:(UITableView *)tableView
  willDisplayCell:(UITableViewCell *)cell
forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [cell setBackgroundColor:[UIColor clearColor]];
}

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

    VideosObject *cell = (VideosObject *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"VideosObject" owner:self options:nil];
        cell = [nib objectAtIndex:0];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Purple Sunrise Pattern iPhone 5 Wallpaper.png"]];

        self.tableView.backgroundView = imageView;
    }

    NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];
    cell.title.text = [movie objectForKey:@"title"];

    NSURL *url = [[NSURL alloc] initWithString:[movie objectForKey:@"link"]];
    [cell.pic setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeholder"]];

    return cell;
}

@end

4 个解决方案

#1


7  

You can save the dictionary that you get after parsing the JSON:

您可以保存解析JSON后获得的字典:

NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

[[NSUserDefaults standardUserDefaults] setObject:result forKey:@"myJSONParsed"];

And to get it back:

并把它拿回来:

NSDictionary *myJSON = [[NSUserDefaults standardUserDefaults] objectforKey:@"myJSONParsed"];

#2


0  

try this code for storing parsed json in nsuserdefaults

尝试使用此代码在nsuserdefaults中存储已解析的json

     NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"link"]];
        AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request 
            success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

                NSDictionary *jsonDict = (NSDictionary *) JSON;
                self.movies = [jsonDict objectForKey:@"putYourKey"];

                //here is the way to add parsed array to NSUserDefaults
                [NSUserDefaults standardUserDefaults] setObject:self.movies forKey:@"moviesArray"];
                [[NSUserDefaults standartUserDefaults] synchronize];

            } failure:^(NSURLRequest *request, NSHTTPURLResponse *response,
                NSError *error, id JSON) {
                    NSLog(@"Request Failure Because %@",[error userInfo]); 
            }
        ];

        [operation start];

#3


0  

After setting value to NSUserDefaults you should to synchronize it:

将值设置为NSUserDefaults后,您应该同步它:

[[NSUserDefaults standardUserDefaults] setObject:someObject forKey:@"someKey"];
[[NSUserDefaults standardUserDefaults] synchronize];

And when you need to access to saved data just get it from defaults for your key:

当您需要访问已保存的数据时,只需从密钥的默认值中获取:

[[NSUserDefaults standardUserDefaults] objectForKey:@"someKey"];

#4


0  

Write this code from where you are getting url data

从您获取网址数据的位置编写此代码

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
username = [[response valueForKey:@"Login"]valueForKey:@"name"];
[defaults setObject:username forKey:@"name"];

In this method retrieve the data:

在此方法中检索数据:

- (void)viewDidLoad
{
    defaults = [NSUserDefaults standardUserDefaults];
    Musrname = [defaults objectForKey:@"name"];
}

#1


7  

You can save the dictionary that you get after parsing the JSON:

您可以保存解析JSON后获得的字典:

NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

[[NSUserDefaults standardUserDefaults] setObject:result forKey:@"myJSONParsed"];

And to get it back:

并把它拿回来:

NSDictionary *myJSON = [[NSUserDefaults standardUserDefaults] objectforKey:@"myJSONParsed"];

#2


0  

try this code for storing parsed json in nsuserdefaults

尝试使用此代码在nsuserdefaults中存储已解析的json

     NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"link"]];
        AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request 
            success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

                NSDictionary *jsonDict = (NSDictionary *) JSON;
                self.movies = [jsonDict objectForKey:@"putYourKey"];

                //here is the way to add parsed array to NSUserDefaults
                [NSUserDefaults standardUserDefaults] setObject:self.movies forKey:@"moviesArray"];
                [[NSUserDefaults standartUserDefaults] synchronize];

            } failure:^(NSURLRequest *request, NSHTTPURLResponse *response,
                NSError *error, id JSON) {
                    NSLog(@"Request Failure Because %@",[error userInfo]); 
            }
        ];

        [operation start];

#3


0  

After setting value to NSUserDefaults you should to synchronize it:

将值设置为NSUserDefaults后,您应该同步它:

[[NSUserDefaults standardUserDefaults] setObject:someObject forKey:@"someKey"];
[[NSUserDefaults standardUserDefaults] synchronize];

And when you need to access to saved data just get it from defaults for your key:

当您需要访问已保存的数据时,只需从密钥的默认值中获取:

[[NSUserDefaults standardUserDefaults] objectForKey:@"someKey"];

#4


0  

Write this code from where you are getting url data

从您获取网址数据的位置编写此代码

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
username = [[response valueForKey:@"Login"]valueForKey:@"name"];
[defaults setObject:username forKey:@"name"];

In this method retrieve the data:

在此方法中检索数据:

- (void)viewDidLoad
{
    defaults = [NSUserDefaults standardUserDefaults];
    Musrname = [defaults objectForKey:@"name"];
}