NSLog没有出现

时间:2014-02-05 04:22:02

标签: ios objective-c json nslog

我试图让NSLog打印出JSON数据。但它不会出现在日志上。我是Objective-C的新手。代码有什么问题?

@implementation demo2ViewController

-(void)viewDidLoad
{
   [super viewDidLoad];
   title = @"title";
   thumbnail = @"thumbnail";
   author = @"author";

   myObject = [[NSMutableArray alloc] init];

   NSData *jsonSource = [NSData dataWithContentsOfURL:
                        [NSURL URLWithString:@""]];
// note : i have the ip address, but stackoverflow wont allow me to post it. so i deleted.


    NSArray*  jsonObjects = [NSJSONSerialization JSONObjectWithData:
                      jsonSource options:NSJSONReadingMutableContainers  error:nil];

    for (NSDictionary *dataDict in jsonObjects) {
        NSString *title_data = [dataDict objectForKey:@"title"];
        NSString *thumbnail_data = [dataDict objectForKey:@"thumbnail"];
        NSString *author_data = [dataDict objectForKey:@"author"];

        NSLog(@"TITLE: %@",title_data);
        NSLog(@"THUMBNAIL: %@",thumbnail_data);
        NSLog(@"AUTHOR: %@",author_data);

        dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                      title_data, title,
                      thumbnail_data, thumbnail,
                      author_data,author,
                      nil];
        [myObject addObject:dictionary];
    }
}

[ { 
title: "Post From Wordpress Title", 
content: "Some Content from Post on Wordpress", 
author: "Banyapon Poolsawasd", thumbnail: "" 
},{ 
title: "Post From Wordpress Title", 
content: "Some Content from Post on Wordpress", 
author: "Banyapon Poolsawasd", 
thumbnail: "" 
 } ]

非常感谢您的帮助。 感谢。

2 个答案:

答案 0 :(得分:0)

尝试NSLog到jsonSource

NSData *jsonSource = [NSData dataWithContentsOfURL:
                    [NSURL URLWithString:@""]]; //Here you are not call url string
NSlog(@"jsonSource:%@", jsonSource);

jsonSource将返回nil

    NSArray*  jsonObjects = [NSJSONSerialization JSONObjectWithData:
                  jsonSource options:NSJSONReadingMutableContainers  error:nil];

 NSlog(@"jsonObjects:%@", jsonObjects);

jsonObjects也将返回nil

所以控制器不会进入for循环,这就是你没有打印的原因..

答案 1 :(得分:0)

您的数据

[ { 
title: "Post From Wordpress Title", 
content: "Some Content from Post on Wordpress", 
author: "Banyapon Poolsawasd", thumbnail: "" 
},{ 
title: "Post From Wordpress Title", 
content: "Some Content from Post on Wordpress", 
author: "Banyapon Poolsawasd", 
thumbnail: "" 
 } ]

在上述情况下,您的数据从NSArray开始,不是NSDictionary 。这就是没有显示任何内容的原因。
使用以下代码获取标题和其他值,如下所示,例如

 NSLog(@"Title :%@",[[jsonObjects objectAtIndex:0]objectForKey:@"title"]);
相关问题