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

时间:2013-12-03 09:28:34

标签: ios json nsuserdefaults

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

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

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

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

稍后再回来:

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

当我解析像这样的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 个答案:

答案 0 :(得分:7)

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

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

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

并将其取回:

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

答案 1 :(得分:0)

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

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

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

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

答案 2 :(得分:0)

从您获取网址数据的地方编写此代码

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

在此方法中检索数据:

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

答案 3 :(得分:0)

尝试使用此代码在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];