开发者

iphone programming: making a MVC-styled app to parse JSON correctly?

开发者 https://www.devze.com 2023-01-08 12:41 出处:网络
I\'m trying to create an iphone app which grabs a JSON string, parses it and displays a list of items in at table view.

I'm trying to create an iphone app which grabs a JSON string, parses it and displays a list of items in at table view.

I'm also attempting to use an Model-View-Controller (MVC) architecture for my project.

My question is in 2 parts:

1) How do I structure开发者_Python百科 my different files to conform to this standard (MVC) ?

2) (more general) I've been going through a lot of XML parsing examples, and they seem to implement standard methods such as 'requestDidFinishLoad', 'setActiveProperty', etc... How can I find out exactly what methods I need to implement to successfully send a request and parse a JSON string?


Your model for your table view will likely be an NSArray or NSDictionary instance. An array is easier for the purposes of demonstration.

The json-framework on Google Code will let you pull a JSON array into an NSArray very easily.

As an example, let's say your table view controller has a retained NSArray property called items.

Then the JSON object here:

{
    "items" : [
        "item1",
        "item2", 
        ...
        "itemN"
    ]
} 

Can be poured into an array as follows:

SBJSON *jsonParser = [[SBJSON alloc] init];
NSDictionary *jsonDictionary = (NSDictionary *) [jsonParser objectWithString:jsonString error:nil];
self.items = (NSArray *) [jsonDictionary objectForKey:@"items"];
[jsonParser release];

Your table view data source delegate just pulls out objects from the items array, e.g.:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [items count];
}

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

    // instantiate or dequeue cell...

    // label cells with JSON item names
    cell.textLabel.text = [items objectAtIndex:indexPath.row];
}


Apple has great documentation on MVC. See this link.

The basic idea is to separate your app into the part responsible for displaying the data (the view), the data itself (the model) and the interface between the two (the controller).

In your case, if you are just parsing and displaying JSON and don't need to save or edit the information, you can cut out the model and do all the work in the controller. Just make a UITableViewController subclass that parses the JSON into an array and uses the array as the data source for the table view. If storing the data permanently is important to you than you want to look at something like plists or CoreData.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号