1

I'm working on an iOS application written in Objective-C and I'm almost done, except for one thing:

I'm parsing a JSON into a tableview, and I want to store the data locally in the app. But I don't know the best way of doing this. Each row has an image, a title, description, and a link. I have different tabs with different JSON.

(I don't want to parse the JSON every time the app opens up, I want to check if something new has been added to the JSON and THEN parse it again. But for now I'm just happy if I can manage to save the data from the JSON locally)

I've been struggling with this for a while now and I really need some help. This is the last thing that I need to fix before the app is ready for App Store.

Don't know if you need to see any code, but I post it anyway so you might get a better understanding of what I'm doing.

Code for parsing json:

 jsonData_ = [[NSMutableData alloc] init];
    NSString *urlString = [NSString stringWithFormat:@"http://www.myUrl.se/json/%@.json", _whatState];
    NSURL *url = [NSURL URLWithString: urlString];
    NSURLRequest *urlReq = [NSURLRequest requestWithURL: url];
    NSURLConnection *connection = [NSURLConnection connectionWithRequest: urlReq delegate:self];


-(void)connectionDidFinishLoading:(NSURLConnection*) connection{

    //NSLog(@"Succeeded! Recieved %d bytes of data", [jsonData_ length]);
    NSError *error;
    NSArray *items = [NSJSONSerialization JSONObjectWithData: jsonData_ options: kNilOptions error: &error];

    NSSortDescriptor *sortDesc = [[[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES]copy];
    NSMutableArray *sortedItems = [NSMutableArray arrayWithObject: sortDesc];
    sortedItems = [[items sortedArrayUsingDescriptors: sortedItems] copy];

    if(!error)
    {
        tableData_ = sortedItems;
        tableImgs_ = [[NSMutableArray alloc] initWithArray: tableData_ copyItems: YES];
        [self.tableView reloadData];
        jsonIsFinishedLoading = TRUE;

    }
    else
    {
        NSLog(@"ERROR");
    }
}

Code for my tableview:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *cellIdentifier = @"listItem";
    TSCustomCell *cell = (TSCustomCell*) [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    [cell setSelectedBackgroundView:selectedCellBgColorView];


    if(jsonIsFinishedLoading)
    {
        NSDictionary *row = [tableData_ objectAtIndex: indexPath.row];
        NSString *title = [row objectForKey:@"title"];

        cell.url = [row objectForKey:@"url"];
        UIFont *defaultFont = [UIFont fontWithName:@"Edmondsans-Bold" size:12.0];

        [cell.listItemLbl setText: title];
        [cell.listItemLbl setFont:defaultFont];


        if([[tableImgs_ objectAtIndex:indexPath.row] isMemberOfClass: [UIImage class]])
            {
                [cell.listItemImage setImage: [tableImgs_ objectAtIndex: indexPath.row]];
            }
            else
            {

                UIActivityIndicatorView *loadingSymbol = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleGray];
                loadingSymbol.frame = cell.listItemImage.frame;
                [cell addSubview: loadingSymbol];
                [loadingSymbol startAnimating];


                dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);

                dispatch_async(queue, ^{


                    NSString *url = [row objectForKey: @"image"];

                    if([url isEqualToString: @""])
                    {
                        url = @"http://www.myUrl.se/images/standard.png";
                    }
                    else
                    {
                        url = [row objectForKey: @"image"];
                    }

                    NSURL *imgUrl = [NSURL URLWithString: url];
                    NSData *imageData = [NSData dataWithContentsOfURL: imgUrl];
                    UIImage *image = [UIImage imageWithData: imageData];

                    if(image != nil)
                    {
                        [tableImgs_ replaceObjectAtIndex:indexPath.row withObject:image];
                        NSLog(@"tableImgs != nil");

                    }
                    else
                    {
                        NSLog(@"tableImgs = nil");
                        [cell.listItemImage setImage: [UIImage imageNamed:@"standard_transp.png"]];
                    }

                    dispatch_sync(dispatch_get_main_queue(), ^{

                        [loadingSymbol removeFromSuperview];
                        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation: UITableViewRowAnimationNone];


                    });  
                }); //end dispatch_async
            }
        }
    }


    return cell;

}

Thanks!!

4

3 回答 3

1

如果我理解你是正确的 - 你可以通过这段代码将你的数据与 JSOn 保存到用户默认值中

[[NSUserDefaults standardUserDefaults] setObject:jsonData_ forKey:@"myData"];

如果你正在解析 json - 你有数据

当你想得到它

jsonData_ = [[NSUserDefaults standardUserDefaults] valueForKey: @"myData"];
于 2013-04-05T13:21:12.567 回答
-2

这是关于使用NSCoding 协议NSFileManager将对象保存到磁盘的有用教程。如果您为每一行创建一个对象,您将能够保存它们。

您也可以使用这种方法来保存 JSON 本身,或者您可以将其存储在用户 defaults中。

# Saving
[[NSUserDefaults standardUserDefaults] setObject:jsonData forKey:@"json data"];
[[NSUserDefaults standardUserDefaults] synchronize]; // Generally happens automatically, but if this might happen close to backgrounding you'll want this

# Loading
jsonData = [[NSUserDefaults standardUserDefaults] objectForKey:@"json data"];
于 2013-04-05T13:25:32.280 回答
-3

使用 AFNetworking 来实现这一点。它比 NSURLConnection 更容易、更快、更好。

在此处阅读更多信息:AFNetworking

于 2013-04-05T13:12:40.917 回答