Your assignments to your two string variables are inside a block you pass to sendTwitterRequest:completion:
. By default a block captures the value of any local variables it uses declared outside the block, in your case r1
and r2
, it does not capture the variables themselves, which means it cannot alter the values stored in those variables. Note that if the value captured is a reference to a mutable object, in your case the values are references to mutable strings, then you can mutate the object - doing that does not alter the reference itself.
You can fix your code in two ways:
1) I think the values you are trying to assign are references to immutable strings, NSString *
, so I suspect you have only declared the two variables as NSMutableString *
in an attempt to fix your problem.
To allow assignment to captured local variables you must annotate the local variable declaration with __block
, this changes the behaviour capture so that the variable, rather than its value, is captured. To go this route you just need to change your declarations to:
__block NSString *r1;
__block NSString *r2;
There is no need to give the variables an initial value, they will automatically have the value nil
. Your block can now assign directly to r1
and r2
, however see the BIG BUT below.
2) If you do require mutable strings, NSMutableString *
, then your two declarations are fine and the issue is that you use assignment to the variables (r1
& r2
) instead of mutating the strings they reference. You can change the value of a mutable string using setString:
(Apple documentation. To do this replace your two assignments with:
[r1 setString:json[@"statuses"][0][@"text"]];
[r2 setString:json[@"statuses"][1][@"text"]];
These two will mutate your strings referenced by variables and those changes will be visible outside your block via the references stored in r1
and r2
. However as with the first method above see the following BIG BUT...
BIG BUT
The code fragment you supply suggests you might also be making a common error: assuming values assigned within a block used as an asynchronous handler will be visible after the call taking the block, in your case sendTwitterRequest:completion:
. This will normally not be true, the call to sendTwitterRequest:completion:
returns before the completion block has run - which is the whole point of asynchronous methods such as sendTwitterRequest:completion:
; they schedule the work (accessingTwitter in your case) to run concurrently in the background and then return, later when the asynchronous work is completed the completion block is called.
If you have made this error you need to read up on asynchronous design, you can use Apple's documentation if you wish, you can also search on SO - there are plenty of Q & A on the topic. After that is done you can redesign your code, if you have problems at that point ask a new question.
HTH