返回列表 回复 发帖

displaying JSON data in table view on iphone

I can parse data and see the output also but i am not able to display them in table view

problem is 1st my tableviews code are executing then rest functions are working that's why i am getting 0 , how to avoid this ??

this is my code

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    NSLog(@" value %d",[jsonArray count]);// always 0
    return  [jsonArray count];
}


in this method also i am getting 0 valuee

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
   *)indexPath {  NSDictionary *aTweet = [jsonArray objectAtIndex:[indexPath
     row]];     NSLog(@ " divy is
     %@",aTweet);// nothing

     }


other codes

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {      
    [connection release];

    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    [responseData release];

    NSError *error;
    SBJSON *json = [[SBJSON new] autorelease];

NSDictionary *data = (NSDictionary *) [json objectWithString:responseString error:nil];  


   NSDictionary *menu = (NSDictionary *) [data objectForKey:@"name"];  
    //label.text=[dict objectForKey:@"firstName"];


     // parsing all the items in to the NSArray  

   NSArray *items = (NSArray *) [menu objectForKey:@"phoneNumber"];  


    int ndx;
    //NSDictionary *stream;
    for (ndx = 0; ndx< items.count; ndx++) {

            stream = (NSDictionary *)[items objectAtIndex:ndx];


        NSLog(@"This is the title of a stream: %@", [stream valueForKey:@"type"]);
        [jsonArray addObject:stream];


    }   

    NSLog(@" aray is %@",jsonArray);// show all data working
    NSLog(@" sterab is %@",[stream valueForKey:@"home"]);// this is also working
and this is my view did load()


- (void)viewDidLoad {   

    jsonArray= [[NSMutableArray alloc] init] ;
        [super viewDidLoad];

    responseData = [[NSMutableData data] retain];      
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://Json/Number.json"]];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];            
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    label.text = [NSString stringWithFormat:@"Connection failed: %@", [error description]];
}


****************************************************
Possibly, the problem is that you data doesn't load immediately. And UITableView, when created, stores necessary data in some sort of cache. This allows to avoid often calls of data source's methods, like tableView:numberOfRowsInSection: and others. So you should explicitly call UITableView's reloadData method to refresh table.

To solve the problem, you should do something like this:

In viewDidLoad just show some spinner to indicate program activity.
In connectionDidFinishLoading: after all data was initialized, call [yourTableView reloadData].

http://stackoverflow.com/questio ... able-view-on-iphone
Hello all working on my building my first iDevice app and I am trying to populate a UITableView with data from json result I can get it to load from plist array no propblem and I can even see my json the problem I'm having is that the UITableView never gets to see the json results please bare with me as this is first time with obj-c or anything like it

in my .h file

@interface TableViewViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> {
    NSArray *exercises;
    NSMutableData *responseData;

}
in my .m file

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  exercises.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //create a cell
    UITableViewCell *cell = [[UITableViewCell alloc]
    initWithStyle:UITableViewCellStyleDefault
    reuseIdentifier:@"cell"];

    // fill it with contnets
    cell.textLabel.text = [exercises objectAtIndex:indexPath.row];
    // return it
    return cell;
}


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {      
    responseData = [[NSMutableData data] retain];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://url_to_json"]];
    [[NSURLConnection alloc] initWithRequest:request delegate:self ];


    // load from plist
    //NSString *myfile = [[NSBundle mainBundle] pathForResource:@"exercise" ofType:@"plist"];
    //exercises = [[NSArray alloc] initWithContentsOfFile:myfile];
    [super viewDidLoad];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Connection failed: %@", [error description]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [connection release];

    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    [responseData release];

    NSDictionary *dictionary = [responseString JSONValue];
    NSArray *response = [dictionary objectForKey:@"response"];

    exercises = [[NSArray alloc] initWithArray:response];
}


********************************************
You need to tell your table view to reload. Try adding:

[tableView reloadData];
at the end of your -connectionDidFinishLoading method.


http://stackoverflow.com/questio ... tableview-from-json
JSON我就不多解释了,需要更多信息的朋友请到json.org上查看。

在iPhone上访问网络内容是很必须的,而一些数据就需要以某种形式储存在web服务器上。比如一个app的目录,内容,索引等等。而xml和json,plist都是比较方便的方式。

-XML在iPhone上是非常好用的,但是对复杂的数据结构使用上就不那么方便了,具体可以参阅苹果的“基于事件的XML”和“基于树的XML”编程向导

-plist是再方便不过了,不过我看最多也就是一个NSDictionary而已,复杂一些的话,数据输入上也会非常非常的麻烦。

-JSON本来是不被苹果支持的,但是有人很Nice的帮我们解决了这个问题:JSON for OBJC http://code.google.com/p/json-framework/

基本上来说,这个框架异常的简单易用,会将得到的json字符串处理成一个复杂NSDictionary对象,而每一个值都还是一个NSDictionary对象

比如:

{
        "华藏净宗学会":
        {
                "zhaomu":
                {
                        "name":"净宗朝暮课本",
                        "length":142,
                        "digits":3
                },
                "kesong":
                {
                        "name":"净宗共修课本",
                        "length":75,
                        "digits":2
                }
        },
        "生命基金会":
        {
                "dabei88":
                {
                        "name":"大悲出相图",
                        "length":88,
                        "digits":2
                }
        }
}
就会转换为一个复杂无比的NSDictionary:

[[NSDictionary alloc]
initWithObjects:[NSArray
                  arrayWithObjects:
                  [NSDictionary
                   dictionaryWithObjects:[NSArray
                                  arrayWithObjects:
                                  [NSDictionary
                                   dictionaryWithObjects:[NSArray
                                                  arrayWithObjects:
                                                          @"净宗朝暮课本",
                                                          @"142",
                                                          @"3",nil]
                                   forKeys:
                                   [NSArray arrayWithObjects:
                                   @"name",
                                   @"length",
                                   @"digits",nil]],
                                  [NSDictionary
                                   dictionaryWithObjects:[NSArray
                                                  arrayWithObjects:
                                                  @"净宗共修课本",
                                                  @"75",
                                                  @"2",nil]
                                   forKeys:
                                   [NSArray arrayWithObjects:
                                   @"name",
                                   @"length",
                                   @"digits",nil]],nil]
                   forKeys:[NSArray arrayWithObjects:@"zhaomu",@"kesong",nil]],
                  [NSDictionary
                   dictionaryWithObjects:[NSArray
                                  arrayWithObjects:
                                  [NSDictionary
                                   dictionaryWithObjects:[NSArray
                                                  arrayWithObjects:
                                                  @"大悲出相图",
                                                  @"88",
                                                  @"2",nil]
                                   forKeys:
                                   [NSArray arrayWithObjects:
                                   @"name",
                                   @"length",
                                   @"digits",nil]],nil]
                   forKeys:[NSArray arrayWithObjects:@"dabei88",nil]],nil]
forKeys:[NSArray arrayWithObjects:@"华藏净宗学会",@"生命基金会",nil]];
我是非常佩服自己能打出来上面的巨大无比的定义式。。。。没有编译错误

不管怎么样,转换后,在系统中就可以非常方便的使用json的键值结构信息咯~!!!

http://c.gzl.name/archives/244
上一期基本上讨论了Objc的JSON框架的原理,现在简单介绍一下使用。

在CS193P的课堂程序上,列出了以下函数:

+ (id)fetchJSONValueForURL:(NSURL *)url
{
    NSString *jsonString = [[NSString alloc] initWithContentsOfURL:url
                                                          encoding:NSUTF8StringEncoding error:nil];

    id jsonValue = [jsonString JSONValue];
    [jsonString release];
    return jsonValue;
}
基本上这个函数方法就是将一个传入的互联网地址,当然是一个.json文件的位置。然后传出的就是一个NSDictionary~

我在使用的时候,写了一个方法来调用它:

+ (NSDictionary *)fetchLibraryInformation
{
    NSString *urlString = [NSString stringWithFormat:@"http://gzl.name/appData/MyFodian/Lib/main.json"];
    NSURL *url = [NSURL URLWithString:urlString];
        NSLog(@"fetching library data");
    return [self fetchJSONValueForURL:url];
}
这个方法不过是将我存放json文件的地址告诉了前面的方法,然后返回这个NSDictionary,这回的返回值我用得NSDictionary,其实和id在这里没有区别。记得在使用这个对象的时候还要retain一下,否则一会儿就没有咯。因为JSONValue方法返回的应该是一个autorelease对象。

接下来我们就可以使用这个NSDictionary中的数据拉!

http://c.gzl.name/archives/313
既然JSON这么好,它怎么和UITableView结合使用呢?

首先看看我们的JSON文件吧:

{
        "老张家":["大张","二张","三张"],
        "老李家":["大李","二李"]
}
完成的作品是这样样子的~~(点击放大阿~~)



好,开始打代码吧。

1,首先copy JSON库到当前的Project里面。



2,建立一个数据源类。我给它起名叫MyDataSource, 看看里面都有什么吧:

@interface MyDataSource : NSObject {}
+ (id)dataSource;
@end

#import "JSON.h"

@implementation MyDataSource
+ (id)dataSource
{
        NSString* JSONString = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"data" ofType:@"json"]
                                                         encoding:NSUTF8StringEncoding error:nil];
        return [JSONString JSONValue];
}
@end
里面非常简单,只有一个类方法dataSource。在其中我们读取json文件的内容到一个NSString中,并用JSON框架来解读成一个NSDictionary,返回值为id。因为虽然大多的时候最外的对象都为NSDictionary,但是出于严谨,万一是NSArray不就崩溃了。所以使用id,这样其实就有再次可以用的特性了。

3,建立一个UITableViewController, 然后作适当的设置:

#import "MyTableViewController.h"
#import "MyDataSource.h"

@implementation MyTableViewController

- (id)initWithStyle:(UITableViewStyle)style
{
        if (self = [super initWithStyle:style]) {
                myData = [[MyDataSource dataSource] retain];
                //在这里我们初始化myData,其实就是一个id对象
                //传入由MyDataSource解析出的NSDictionary
        }
        return self;
}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [myData count];    //有多少个section,也就是“几家”
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[myData valueForKey:[[myData allKeys] objectAtIndex:section]] count];
//这里我们需要告诉UITableViewController每个section里面有几个,也就是“一家里面有几口人”
}

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

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                                reuseIdentifier:CellIdentifier] autorelease];
    }
   //上面的东西都是重复白给的,平时没事不用想为什么,照抄就可以了
        cell.textLabel.text = [[myData valueForKey:[[myData allKeys] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
        //这句看上去复杂,但是其实不过是在特定section里面找到对应的array,
        //然后在array中找到indexPath.row所在的内容
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
        return [[myData allKeys] objectAtIndex:section];
//这里设置对应section的名字,很简单allKey返回所有的键值为一个array,也就是“张家”,“李家”
//然后用objectAtIndex: 来找出究竟是哪一个就可以了!
}

- (void)dealloc {
    [myData release]; //“我们是runtime的好市民”...release就好Alan......
    [super dealloc];
}
@end
4,在主程序代理 xxxAppDelegate 里面初始化这个UITableViewController然后添加它的view到window的subview中就OK拉!

5,编译运行,没有错误就万事大吉!大吉!

阿弥陀佛,祝各位愉快~

http://c.gzl.name/archives/318
So i'm working on an iphone app that parses json and tries to put the results into a plain UITableview. I have my tableview setup in the xib file and also setup the datasource and the delegate as the MainViewController (this is utility application). I get the JSON request just fine and I always test this by outputting it to a text label. But when I debug and hover over the cellData var (which holds this data), it shows out of scope, and my simulator shows an empty table that won't scroll...like it's stuck waiting for something to finish.

Here is my header for the view controller:

#import "FlipsideViewController.h"

@interface MainViewController : UIViewController <FlipsideViewControllerDelegate,     UITableViewDelegate, UITableViewDataSource> {
IBOutlet UILabel *label;
UITableView *theTableView;
NSMutableArray *cellData;

}
@property (nonatomic, retain) IBOutlet UILabel *label;
@property (retain) NSMutableArray *cellData;
- (IBAction)showInfo:(id)sender;

@end
and here is my implementation:

#import "MainViewController.h"
#import "JSON.h"


@implementation MainViewController
@synthesize label;
@synthesize cellData;
//Begin code for Table View Data Source (required methods)

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //how many rows in the section; for testing purposes...placed here
    return [cellData count];
    //return 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //create a cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];     
    }

    //fill it with contents
    cell.textLabel.text = [cellData objectAtIndex:indexPath.row];
    //return it
    return cell;
}

//End code for Table View Data Source

//Begin code for JSON stuffs

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];

    //TODO: need to extract this code out to a function because need to make multiple requests per run of the app....
    //responseData = [[NSMutableData data] retain];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://tabular.heroku.com/tab_stores/tester.json"]];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
    cellData = [[NSMutableArray alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{

    NSMutableData *mutData = [[NSMutableData alloc] init];
    [mutData appendData:data];

    NSString *responseString = [[NSString alloc] initWithData:mutData encoding:NSUTF8StringEncoding];

    NSArray *responseData = [responseString JSONValue];

    NSMutableString *text = [NSMutableString stringWithString:@"T:"];

    for (int i = 0; i < [responseData count]; i++)
        [text appendFormat:@"%@\n", [responseData objectAtIndex:i]];

    label.text =  text;

    NSLog(@"%@\n", cellData);
    //Let's parse the data the way its supposed to be

    //for every window, there should be a section.
    for (int i=0; i<[responseData count]; i++) {
        //manage table section
        //maybe print window 1

    }


    //[cellData addObject:[responseData objectAtIndex:0]];
    [cellData addObjectsFromArray:responseData];
//  [responseData release];
    NSLog(@"%@\n", cellData);


    [theTableView reloadData];

    [responseString release];
    [mutData release];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    label.text = [NSString stringWithFormat:@"Connection failed: %@", [error description]];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [connection release];

    //NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

    //[responseData release];

    //cellData = [responseString JSONValue];

    //NSLog(@"this is in tabs %@", tabs);
//  NSLog(@"this is in cellData %@", cellData);
//      NSLog(@"this is in cellDatas %@", cellDatas);

    //NSMutableString *text = [NSMutableString stringWithString:@"T:"];

//  for (int i = 0; i < [cellDatas count]; i++)
//      [text appendFormat:@"%@\n", [cellDatas objectAtIndex:i]];

//  label.text =  text;

    //[theTableView reloadData];
}


//End code for JSON stuffs

.
.
.

- (void)dealloc
{
  [theTableView release];
//[cellData release];
  [super dealloc];
}
I know that the tableview calls those functions for number of sectionsiInTableView and numberOfRowsInSection first so it won't get the data, but then I thought calling reloadData would work...but nothing. Can anyone help a newbie out?

*NSLogs in console:

2010-08-15 15:42:07.421 Tabular[33046:207] (
)
2010-08-15 15:42:09.902 Tabular[33046:207] (
    (
            (
        Google,
        "https://www.google.com/"
    ),
            (
        "https://tabular.heroku.com/tab_stores/tester",
        "https://tabular.heroku.com/tab_stores/tester"
    ),
            (
        "test - Google Search",
        "http://www.google.com/search?client=safari&rls=en&q=test&ie=UTF-8&oe=UTF-8"
    ),
            (
        "Using POST method in XMLHTTPRequest(Ajax)",
        "http://www.openjs.com/articles/ajax_xmlhttp_using_post.php"
    ),
            (
        "json stringify - Google Search",
        "http://www.google.com/search?client=safari&rls=en&q=json stringify&ie=UTF-8&oe=UTF-8"
    ),
            (
        "json.stringify escape - Google Search",
        "http://www.google.com/search?q=json.stringify escape&hl=en&safe=off&client=safari&rls=en&ei=PUlaTNiYL4O78gbt8bXsAg&start=10&sa=N"
    )
),
    (
            (
        Google,
        "https://www.google.com/"
    )
)
)


http://stackoverflow.com/questio ... ont-display-the-cel
JSON是一种新的用于在互联网上进行数据交换的标准格式。由于它的冗余、可读性和可解析性都比XML要好,因此JSON这种数据交换格式越来越广泛地运用于Web应用,尤其是Ajax应用中。

在Cocoa中使用JSON也很简单,目前有两个JSON的框架,都很容易使用,而且都对NSDictionary进行了扩展,您可以选择其一将JSON“揉”到您的Cocoa应用程序里。


一个叫做BSJSonAdditions,
由Blake Seely开发。将NSDictionary对象转成JSON字符串只需要进行如下转换:

[dict jsonStringValue];

就可以返回一个NSString的JSON格式。

反过来如果希望将JSON字符串转成NSDictionary,只需要进行如下转换:



[NSDictionarydictionaryWithJSONString:jsonString]



就可以返回NSDictionary的对象了。



NSMutableDictionary *dlist = [[NSMutableDictionary alloc] init];
    [dlist setObject:@"name1" forKey:@"name"];            

NSString *str = [dlist JSONRepresentation];   
NSMutableDictionary *d = [str JSONValue];   
NSLog(@"%@" , [d description]);        
[dlist release];

de>NSString* stringData =[[NSString alloc] initWithData:yourData                                             encoding:NSUTF8StringEncoding];de>
de>NSDictionary* jsonDictionary =[NSDictionary dictionaryWithObject:stringData                                                           forKey:@"code"];de>
de>NSString* jsonString =[jsonDictionary JSONRepresentation];de>
de>NSDictionary* responseDict =[yourJSONResponseStringFromServer JSONValue];
NSNumber* answerNum =(NSNumber*)[responseDict objectForKey:@"answer"];
int answer =[answerNum intValue];de>



另一个叫做json-framework

参考了BSJSonAdditions,并且以framework的方式提供。



json- framework的用法同样类似,使用NSDictionary或者NSArray的JSONRepresentation方法来获取JSON的 NSString字符串,用NSString的JSONValue方法来获取转换后的NSDictionary或者NSArray对象。





JSON framework supports converting Arrays, Dictionaries, Strings, Numbers, and Booleans. So what you want to do is convert your data to one of these formats. Since your data is NSData easiest way is to convert it with:

Depending on what's in the buffer (and if your server can handle it) you may want to Base64 encode the result (check http://www.cocoadev.com/index.pl?BaseSixtyFour if you don't have a converter handy). You could even go straight from NSData to a Base64-encoded string.

Now create a dictionary with one item with key de>codede> and value de>stringDatade> (from last step):

This can be easily converted to JSON. Just import JSON.h in your code header, then use:

Dump it out and you'll see your JSON string -- something like: { de>"code" : "{yourstringdata}"; }de>. Easiest way to send this over to your server is to use the ASIHTTPRequest library with a POST method.

Once you get the result back from the server the JSON framework can parse it back into a dictionary and then you can get out the data you need:

http://blog.csdn.net/boyjimeking/article/details/6773555
這筆記來自於
CS 193P iPhone Application Development
2010 Winter 課程 - 9. Data in Your iPhone App (February 2, 2010) ,另外,關於申請使用 Flickr API 的部份,可以參考
[PHP] 申請使用 Flickr API 教學筆記 - 以 flickr.photos.search 為例
,另外,此例還會用到 UITableView ,可參考
iPhone 開發教學 - 使用 UITableView & UITableViewController 提供表單服務

越來越多網路服務提供 API 讓其他平台可以更簡單地連結到,並且常常使用 JSON 的資料格式來提供多元且方便的 UI 應用,在此,挑選 Flickr API 當作範例,透過對 Flickr 搜尋特定 Tag 後,把找到的圖片資訊利用 UITableView 顯示出來!
此篇目的:
  • 使用 JSON 的方式
  • 使用 NSDictionary 的 Key-Value Pair 來製作 REQUEST URL(如
    PHP - http_build_query
流程:
  • 下載 JSON (json-framework)
    • This framework implements a strict JSON parser and generator in Objective-C.
  • [Xcode]->[Create a new Xcode project]->[iPhone OS]->[Application]->[Window-based Application]-> 此例以 MyJSONTest 為例
    • [Xcode]->[File]->[Cocoa Touch Class]->[UIViewController subclass] (勾選 UITableViewController subclass) -> 此例以 MyTableList 為例
  • 將下載回來的 JSON 打開,並把其中一個目錄 JSON 移到 Project 適當的位置
    • 可以一開始先用 #import "JSON.h" 並編譯看看,若沒問題代表可以找到
程式碼:

MyJSONTestAppDelegate.h

#import <UIKit/UIKit.h>
#import "MyTableList.h"

@interface MyJSONTestAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    MyTableList *myList;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;

@end

MyJSONTestAppDelegate.m

#import "MyJSONTestAppDelegate.h"

@implementation MyJSONTestAppDelegate

@synthesize window;

- (void)applicationDidFinishLaunching:(UIApplication *)application {   
    myList = [[MyTableList alloc] init];
   
    [window addSubview:myList.view];
    // Override point for customization after application launch
    [window makeKeyAndVisible];
}

- (void)dealloc {
    [myList release];
    [window release];
    [super dealloc];
}

@end

MyTableList.h

#import <UIKit/UIKit.h>
#define FLICKR_API_KEY @"YOUR_API_KEY"

@interface MyTableList : UITableViewController {
    NSMutableArray *dataSource;
}

@end

MyTableList.m

#import "MyTableList.h"
#import "JSON.h"

@implementation MyTableList

- (NSString*)http_build_query:(NSString *)targetUrl options:(NSMutableDictionary *) args {
    NSMutableString * url = [[NSMutableString alloc] initWithString:targetUrl];
    NSStringEncoding encoding = NSUTF8StringEncoding;
    BOOL first_in = YES;
    for ( id key in [args allKeys] ) {
        if (first_in) {
            first_in = NO;
            [url appendFormat:@"%@=%@",
                [[NSString stringWithFormat:@"%@", key] stringByAddingPercentEscapesUsingEncoding:encoding],
                [[NSString stringWithFormat:@"%@",[args objectForKey:key]] stringByAddingPercentEscapesUsingEncoding:encoding]
            ];
        } else {
            [url appendFormat:@"&%@=%@",
                [[NSString stringWithFormat:@"%@", key] stringByAddingPercentEscapesUsingEncoding:encoding],
                [[NSString stringWithFormat:@"%@",[args objectForKey:key]] stringByAddingPercentEscapesUsingEncoding:encoding]
            ];
        }
    }
    return [url autorelease];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    dataSource = [[NSMutableArray alloc] init];

    NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
    [data setValue:@"flickr.photos.search" forKey:@"method"];
    [data setValue:@"json" forKey:@"format"];
    [data setValue:@"1" forKey:@"nojsoncallback"];
    [data setValue:FLICKR_API_KEY forKey:@"api_key"];
    [data setValue:@"10" forKey:@"per_page"];
    [data setValue:@"台灣 正妹" forKey:@"tags"];
   
    NSURL *target = [[NSURL alloc] initWithString:[self http_build_query:@"http://api.flickr.com/services/rest/?" options:data]];
    //NSLog( [NSString stringWithFormat:@"%@" , target] );
   
    NSString *jsonResult = [NSString stringWithContentsOfURL:target encoding:NSUTF8StringEncoding error:nil];
    //NSLog( jsonResult  );
   
    //SBJSON *parser = [[SBJSON alloc] init];
    //NSDictionary *formatedData = [parser objectWithString:result error:nil];
   
    NSDictionary *result = [jsonResult JSONValue];
    //NSLog( [NSString stringWithFormat:@"JSONParsing:%d", [result count] ]);
    //NSLog( [NSString stringWithFormat:@"Photos:%d", [[result objectForKey:@"photos"] count] ]);
    //NSLog( [NSString stringWithFormat:@"PhotosArray:%d", [[[result objectForKey:@"photos"] valueForKeyPath:@"photo"] count]]);
   
    // http://www.flickr.com/services/api/misc.urls.html
    id obj;
    for( NSDictionary *photo in [[result objectForKey:@"photos"] valueForKeyPath:@"photo"] ) {
        //NSLog( [NSString stringWithFormat:@"Title:%@", [photo objectForKey:@"title"] ] );
        //NSLog( [NSString stringWithFormat:@"URL:%@", [NSString stringWithFormat:@"http://farm%@.static.flickr.com/%@/%@_%@_s.jpg", [photo objectForKey:@"farm"] , [photo objectForKey:@"server"] , [photo objectForKey:@"id"] , [photo objectForKey:@"secret"]] ] );
        
        [dataSource addObject:
            [[NSDictionary alloc] initWithObjectsAndKeys:
                ( ( (obj = [photo objectForKey:@"title"]) && [obj length] > 0 ) ? obj : @"Untitled" ) ,
                @"title" ,
                [NSString stringWithFormat:@"http://farm%@.static.flickr.com/%@/%@_%@_s.jpg", [photo objectForKey:@"farm"] , [photo objectForKey:@"server"] , [photo objectForKey:@"id"] , [photo objectForKey:@"secret"]],
                @"url" ,
                nil
            ]
        ];
    }
   
    [target release];
    [data release];
   
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
   
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


#pragma mark Table view methods

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


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //NSLog( [NSString stringWithFormat:@"Cnt:%d" , [dataSource count]] );
    return [dataSource count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    static NSString *CellIdentifier = @"Cell";
   
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Set up the cell...
    cell.textLabel.text = [[dataSource objectAtIndex:indexPath.row] objectForKey:@"title"];
    //NSLog( [NSString stringWithFormat:@"%@", [[dataSource objectAtIndex:indexPath.row] objectForKey:@"title"]] );

    cell.imageView.image = [UIImage imageWithData:
                                [NSData dataWithContentsOfURL:
                                    [NSURL URLWithString:
                                        [[dataSource objectAtIndex:indexPath.row] objectForKey:@"url"]
                                    ]
                                ]
                            ];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
    // AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
    // [self.navigationController pushViewController:anotherViewController];
    // [anotherViewController release];
}

- (void)dealloc {
    [dataSource release];
    [super dealloc];
}

@end

在此實作一個 http_build_query 來使用,目前流程上可以取得 Flickr API 回傳的訊息,並且在組出照片出來,但是,我在模擬器上跑的結果還滿慢的,此例利用 "台灣正妹" 找 10 張照片來呈現,若只印照片名稱不慢,但加上讀出縮圖部分,花 5 秒鐘才跑出來,或許還有一些技術可以嘗試看看。

http://changyy.pixnet.net/blog/p ... -%E8%B3%87%E6%96%99
上面用到了json传递的数据,有关json部分,iphone sdk虽然没有支持,但是第三方已经写好了。
json 参考:http://code.google.com/p/json-framework/
下面是具体的代码实现:
数据加载:
    #import “MyDataSource.h”

    #import “JSON.h”

    @implementation MyDataSource

    +(NSDictionary*)fetchLibraryInformation

    {

    NSString*urlString =[NSString stringWithFormat:@"http://wangjun.easymorse.com/wp-content/video/hello.jison"];

    NSURL *url =[NSURL URLWithString:urlString];

    NSLog(@”fetching library data”);

    return[self fetchJSONValueForURL:url];

    }

    +(id)fetchJSONValueForURL:(NSURL *)url

    {

    NSString*jsonString =[[NSString alloc] initWithContentsOfURL:url

    encoding:NSUTF8StringEncoding error:nil];

    id jsonValue =[jsonString JSONValue];

    [jsonString release];

    return jsonValue;

    }

    @end

table数据展示:
    #import “JSONTableTestViewController.h”

    #import “MyDataSource.h”

    @implementation JSONTableTestViewController

    @synthesize myData;

    -(void)viewDidLoad {

    NSLog(@”加载数据“);

    myData =[[MyDataSource fetchLibraryInformation] retain];

    }

    -(void)didReceiveMemoryWarning {

    // Releases the view if it doesn’t have a superview.

    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren’t in use.

    }

    -(void)viewDidUnload {

    // Release any retained subviews of the main view.

    // e.g. self.myOutlet = nil;

    }

    -(NSInteger)numberOfSectionsInTableView:(UITableView*)tableView {

    return[myData count];//有多少个section,也就是“几家”

    }

    -(NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {

    return[[myData valueForKey:[[myData allKeys] objectAtIndex:section]] count];

    //这里我们需要告诉UITableViewController每个section里面有几个,也就是“一家里面有几口人”

    }

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

    staticNSString*CellIdentifier= @”Cell”;

    UITableViewCell*cell =[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if(cell ==nil){

    cell =[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault

    reuseIdentifier:CellIdentifier] autorelease];

    }

    //上面的东西都是重复白给的,平时没事不用想为什么,照抄就可以了

    cell.textLabel.text =[[myData valueForKey:[[myData allKeys] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];

    //这句看上去复杂,但是其实不过是在特定section里面找到对应的array,

    //然后在array中找到indexPath.row所在的内容

    return cell;

    }

    -(NSString*)tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section

    {

    return[[myData allKeys] objectAtIndex:section];

    //这里设置对应section的名字,很简单allKey返回所有的键值为一个array,也就是“张家”,“李家”

    //然后用objectAtIndex: 来找出究竟是哪一个就可以了!

    }

    -(void)dealloc {

    [myData release];

    [super dealloc];

    }

    @end

http://www.cnblogs.com/sky7034/archive/2011/03/23/1992415.html
json-framework
json-framework被广泛的使用,包括iphone OS 本身也用到了这个库。json是目前网络服务API中最常见数据格式,几乎所有的API都是使用的json格式。json-framework可以提供给开发者通过objective-c建立json字串或者解码json字串。

安装方式
下载json-framework解压后Classes文件夹存放了所以需要的文件,将该文件夹加入到项目中,只需要将这个文件夹拖放到Xcode的左边视窗中即可。
在需要使用json-framework功能的源文件中,只需要在源码头部加入:
#import "JSON.h"
即可。

使用方式
NSURL *url = [NSURL URLWithString:@"http://xxxxxx"];
NSString *JSONString = [NSString stringWithContentOfURL:url encoding:NSUTF8StringEncoding error:nil];
这里就是使用json-framework提供的方法来解析字符串,将解析的结果存储为NSDictionary中:
NSDictionary *items = [JSONString JSONValue];
可以使用 NSLog来确认解析的结果,或者是通过objectForKey,valueForKey等方法来取得JSON中的值:
NSLog(@"JSON DATA : %@", [items description]);
将NSDictionary转换成JSON字串:
NSString *JSONString = [items JSONFragment];

注意
JSONValue的返回值以及JSONFragment的调用对象可能会是NSArray, NSNumber, NSSting或者是NSNull。

https://www.google.fr/#hl=fr& ... ;pbx=1&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.,cf.osb&fp=c2ac5c5431a28661&biw=1400&bih=949
返回列表