【发布时间】:2012-02-11 07:07:14
【问题描述】:
是否可以为局部变量分配一个范围在块之外的值并让它保留其值?特别是,我正在为 iOS 编码,并且我在另一个块内有一个嵌套块,我想在块内为 NSString 分配一个值,然后(在块外)使用它。当我在块后引用 NSString 时,我尝试使用 __block nut,我得到一个错误的访问错误。我正在使用 ARC,这很重要。例如:
__block NSString *str;
someBlock ^(id param1)
{
str = @"iPhone";
}
[str getCharAtIndex:1]; //or w/e
我在概念上做错了什么,或者这是不允许的还是什么?非常感谢您的帮助。
编辑:
这是实际代码,基本上代码将推文作为 json 对象获取,然后我要做的就是显示文本。在我没有从 json 中提取文本的代码中,我试图做一个概念证明
- (IBAction)getTweet:(id)sender
{
__block NSString *displayStr;
//account instance
ACAccountStore *store = [[ACAccountStore alloc] init];
ACAccountType *twitterAcountType =
[store accountTypeWithAccountTypeIdentifier: ACAccountTypeIdentifierTwitter];
//request access
[store requestAccessToAccountsWithType: twitterAcountType withCompletionHandler:
^(BOOL granted, NSError *error)
{
if (!granted) {
//display error on textView
}
else
{
//get available accounts
NSArray *twitterAccounts = [store accountsWithAccountType: twitterAcountType];
if([twitterAccounts count] > 0)
{
//get first account
ACAccount *account = [twitterAccounts objectAtIndex: 0];
////make authenticated request to twitter
//set-up params
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
[params setObject:@"1" forKey:@"include_entities"];
[params setObject:@"1" forKey:@"count"];
//which REST thing to call
NSURL *url =
[NSURL URLWithString:@"http://api.twitter.com/1/statuses/home_timeline.json"];
//create request
TWRequest *request =
[[TWRequest alloc]
initWithURL:url parameters:params requestMethod:TWRequestMethodGET];
//attach account info
[request setAccount: account];
[request performRequestWithHandler:
^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if(error != nil)
{
//display error
}
else
{
NSError *jsonError;
NSArray *timeline =
[NSJSONSerialization
JSONObjectWithData: responseData
options: NSJSONReadingMutableLeaves
error: &jsonError];
if (jsonError == nil)
{
///////////////////////////
///heres the src of error//
///////////////////////////
//display data
NSLog(@"array: %@", timeline);
displayStr = @"whats the deal with this";
//i tried this but i think ARC takes care of this
[displayStr retain];
}
else
{
//display error
}
}
}];//end block de request
}
else
{
//display error
}
}
}];//end block de store
///////then heres where i get the bad access error
[self.lastTweetText setText:displayStr];
}//end getTweet
也感谢大家的帮助
【问题讨论】:
标签: iphone objective-c ios ipad ios5