Obj-C:__blockvariables

是否有可能分配一个局部variables的范围是在一个块以外的值,并保留它的值? 特别是,我编码的iOS和我有一个嵌套块内的另一个块,我想分配一个NSString值块内的价值和稍后(块外)使用它。 我试图使用__block螺母时,我指的是NSString块后,我得到一个不良的访问错误。 我正在使用ARC是重要的。 例如:

__block NSString *str; someBlock ^(id param1) { str = @"iPhone"; } [str getCharAtIndex:1]; //or w/e 

我在做一些概念上的错误或不允许或者什么? 非常感谢帮助。

编辑:

这里是实际的代码,基本上代码得到的鸣叫作为一个JSON对象,然后我要做的就是显示文本。 在代码中,我没有从json中提取文本,我试图做一个概念certificate

 - (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 

也感谢帮助家伙

首先,只有在块被执行后, str才会被更新。 所以除非你使用dispatch_sync作为该块,否则在这一行: [str getCharAtIndex:1]; 该块不太可能被执行, str将不会被更新。

其次,如果你不使用ARC,__blockvariables不会被块对象自动保留。 这意味着如果你不保留它,比你访问strstr可能是一个解除分配的对象,并崩溃你的应用程序。

你只是定义该块,但不执行它。 调用someBlock(valueForParam1); 执行你的块。 否则你的str指针指向一些垃圾,并调用getCharAtIndex:崩溃你的应用程序。

你只是简单地定义你的块,但不能调用它。

尝试这个 :)

 __block NSString *str; void (^someBlock)(id) = ^(id param1) { str = @"iPhone"; }; someBlock(nil); [str getCharAtIndex:1]; 

在这种情况下,我直接调用它,但通常块本身是一些方法或函数的参数。