0

我正在使用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);
}

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

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

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

4

2 回答 2

1

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

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

于 2013-09-16T22:35:42.927 回答
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
 }
于 2013-09-16T22:37:22.760 回答