坚持使用JSONModel和NSMutableArray

时间:2013-09-16 22:29:05

标签: ios objective-c nsmutablearray jsonmodel

我正在使用JSONModel从简单的Web服务中检索数据。我需要将key @"message"的值放入一个可变数组中。

 - (void)viewDidLoad
{
     [super viewDidLoad];
     self.delegate = self;
     self.dataSource = self;

     NSString *conversationid = @"xx";
     NSString *callURL = [NSString stringWithFormat:@"http://mydomain.com/inbox_messages.php?conversation=%@", conversationid];

     _feed = [[MessageFeed alloc] initFromURLWithString:callURL
            completion:^(JSONModel *model, JSONModelError *err)
     {
          self.messages = [[NSMutableArray alloc]initWithObjects:[_feed.messagesinconversation valueForKey:@"message"], nil];
          NSLog(@"messages %@", self.messages);
     }];
     NSLog(@"test %@", self.messages);
}

我遇到的问题是,当NSLog(@"messages %@", self.messages);返回所有正确的数据时,NSLog(@"test %@", self.messages);会返回(null)

变量在我班的.h中声明为:@property (strong, nonatomic) NSMutableArray *messages;

这可能是一个菜鸟问题,但我是一个初学者,如果有人能给我指向正确的方向,我会非常高兴。

2 个答案:

答案 0 :(得分:1)

您的NSLog for self.messages在完成块之外。加载数据后调用完成块。创建MessageFeed请求后立即调用该日志。因此,当然,对象self.messages为null,因为请求尚未完成。

解决方法是在完成块中处理所有解析,或者调用另一个类方法来解析接收到的数据。

答案 1 :(得分:0)

你的NSLog后调用你的完成处理程序(“test%@”,self.messages);是

块通常同时发生,并且当某个事件发生时,如此处的完成处理程序或有时是错误处理程序。通过查看代码,您可能会得到类似的内容:

测试无 消息

因此,您的MessageFeed对象正在运行,但它会继续执行您的代码,并首先在完成处理程序范围之外运行NSLog。当您的JSON对象已经下载(之后发生)并解析它然后运行完成处理程序。

 - (void)viewDidLoad
{
[super viewDidLoad];
self.delegate = self;
self.dataSource = self;

NSString *conversationid = @"xx";
NSString *callURL = [NSString stringWithFormat:@"http://mydomain.com/inbox_messages.php?conversation=%@", conversationid];

_feed = [[MessageFeed alloc] initFromURLWithString:callURL //this method takes some time to complete and is handled on a different thread.
            completion:^(JSONModel *model, JSONModelError *err)
         {
             self.messages = [[NSMutableArray alloc]initWithObjects:[_feed.messagesinconversation valueForKey:@"message"], nil];
             NSLog(@"messages %@", self.messages); // this is called last in your code and your messages has been has been set as an iVar.
         }];
  NSLog(@"test %@", self.messages); // this logging is called immediately after initFromURLWithString is passed thus it will return nothing
 }