如何让NSArray摆脱for循环

时间:2014-05-25 02:42:53

标签: ios objective-c asynchronous nsarray

我无法使用以下代码:

.h代码

@property (strong, nonatomic) NSArray * messages;
@property (strong, nonatomic) __block NSMutableArray *m1;

.m代码     NSArray *消息;

NSString *posts;
NSArray* scoreArray;
@synthesize m1;


-(void)awakeFromNib {

PFQuery *query = [PFQuery queryWithClassName:@"Messages"];



[query orderByDescending:@"createdAt"];

[query includeKey:@"message"];






[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (!error) {
        // The find succeeded.
        NSLog(@"Successfully retrieved %d scores.", objects.count);
        // Do something with the found objects
        for (PFObject *object in objects) {
            NSLog(@"%@", object.objectId);
            PFObject *post = object[@"body"];



            m1 = [[NSMutableArray alloc] init];




            posts = [object objectForKey:@"body"];
            [m1 addObject:posts];

            NSLog(@"retrieved related post: %@", posts);

             scoreArray = [query findObjects];

            NSLog(@"Array: %@", scoreArray);


            m1 = [[NSMutableArray alloc]init];
            [m1 addObjectsFromArray:objects];
            _messages = [m1 valueForKey:@"body"];




        }
    } else {
        // Log details of the failure
        NSLog(@"Error: %@ %@", error, [error userInfo]);
    }

}];

NSLog(@"%@",[_messages objectAtIndex:0]);
    [super awakeFromNib];
}

最后一个NSLog没有显示任何内容......我认为我没有正确地声明变量,但不知道如何解决它。谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

在“后台”运行代码时,无法保证订购。

安排后台操作( findObjectsInBackgroundWithBlock:)的调用将立即返回给调用者。之后,片刻之后,您的最终 NSLog 将会运行。

传递给 findObjectsInBackgroundWithBlock:的块将在以后的某个时间执行。