kaymas
kaymas

Reputation: 337

How to keep a reference alive in outside of a block (ARC Enabled)?

My question is about keeping a reference alive outside of a completion handler block. First, Please look at my TableViewController:

@interface KMTweetTableViewController : 
UITableViewController

@property (weak) ACAccount      
 *selectedAccount;

@property  NSMutableArray  *tweetTextBank ;

@end

In the - (void)viewDidLoad Method of KMTweetTableViewController I created a SLRequest instance named userTimeLineRequest. As it turns out, it is responsible for requesting twitter for the user's Timeline.

Then, I tried to make an array from statuses "text" property. I used this piece of code to do that:

[userTimeLineRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSArray *userTimeline = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:Nil];
            int counter ; NSMutableArray *returner = [NSMutableArray alloc]  ;
            for (counter= 1 ; counter <= userTimelineCountReference ; counter++) {
                NSDictionary  *status = [userTimeline objectAtIndex: counter-1]   ;
                NSString  *tweetText = [status objectForKey:@"text"];
                [self.tweetTextBank addObject:tweetText ];
            }
            NSLog(@"%@" , self.tweetTextBank) ;
        });

    }];

The code in dispath_async block works well but when NSLog() fires, I just get null. I think this is because the reference of tweetTexts get terminated at the end of dispath_async block... So what can I do in this case to keep that reference alive when ARC is enabled?

Thank you all

Upvotes: 1

Views: 89

Answers (2)

Hussain Shabbir
Hussain Shabbir

Reputation: 15025

As you have not initialized the array so you are getting null. So first you need to initialize the mutable array.

self.tweetTextBank=[NSMutableArray array];

Upvotes: 2

Lithu T.V
Lithu T.V

Reputation: 20021

Initialise the mutablearray properly then add objects to it

self.tweetTextBank=[[NSMutableArray alloc]initWithCapacity:3];
[userTimeLineRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSArray *userTimeline = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:Nil];
            int counter ; 
            for (counter= 1 ; counter <= userTimelineCountReference ; counter++) {
                NSDictionary  *status = [userTimeline objectAtIndex: counter-1];
                NSString  *tweetText = [status objectForKey:@"text"];
                [self.tweetTextBank addObject:tweetText ];
            }
            NSLog(@"%@" , self.tweetTextBank) ;
        });

    }];

Upvotes: 2

Related Questions