0

我对 NSMutableArray 有一个重大问题,我可能遗漏了一些非常明显的东西——可能一直在看它,以至于我看不到它。

我正在阅读一些推文,然后使用结果来填充 NSMutableArray :

@synthesize testArray;

- (void)viewDidLoad{

        [super viewDidLoad];

        testArray = [[NSMutableArray alloc] init];

        TWRequest *request = [[TWRequest alloc] initWithURL:[NSURL URLWithString:@"http://search.twitter.com/search.jsonq=kennedy&with_twitter_user_id=true&result_type=recent"]
        parameters:nil requestMethod:TWRequestMethodGET];

       [request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
       {
        if ([urlResponse statusCode] == 200) {

            // The response from Twitter is in JSON format
            // Move the response into a dictionary
            NSError *error;
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
            NSArray *results = [dict objectForKey:@"results"];

            //Loop through the results
            for (NSDictionary *tweet in results) {

                tweetStore *tweetDetails = [[tweetStore alloc] init];
                NSString *twitText = [tweet objectForKey:@"text"];

                //Save the tweet to the twitterText array
                tweetDetails.name = @"test";
                tweetDetails.date = @"test";
                tweetDetails.tweet = twitText;

                [testArray addObject:tweetDetails];
            }

            tweetStore *retrieveTweet = (tweetStore*)[testArray objectAtIndex:0];
            NSLog(@"tweet is: %@", retrieveTweet.tweet);
            //NSLog(@"Array is: %@", testArray); - *can* view Array etc here
        }

         else {
               NSLog(@"Twitter error, HTTP response: %i", [urlResponse statusCode]);
         }
    }
     ];


    NSLog(@"test array: %@", testArray); //Array is now empty......
}

我可以在我标记它的代码中查看数组,检索我想要的对象等,它工作得很好。但是,一旦我尝试访问或显示数组之外的任何内容,它似乎就是空的。任何帮助或指示将不胜感激。

4

1 回答 1

0

The problem is that the code in the block is performed in an asynchronous way, so it is executed after the NSLog code.

The code executed follows this flow:

  • First you perform the initialization:

    [super viewDidLoad];
    
    testArray = [[NSMutableArray alloc] init];
    
    TWRequest *request = [[TWRequest alloc] initWithURL:[NSURL URLWithString:@"http://search.twitter.com/search.jsonq=kennedy&with_twitter_user_id=true&result_type=recent"]
    parameters:nil requestMethod:TWRequestMethodGET];
    
  • You start the request:

    [request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) { <block_code> } ];
    
  • You print array information and it is empty (correct):

    NSLog(@"test array: %@", testArray);
    

Now the asynchronous request ends and the code in the block is executed: so the array is populated correctly only in the block code.

于 2013-05-20T11:40:02.180 回答