繁体   English   中英

Obj-C:__block变量

[英]Obj-C: __block variables

是否可以为局部变量分配一个范围在块外的值并保留其值? 特别是,我正在为iOS进行编码,并且在另一个块内有一个嵌套块,并且我想为NSString在该块内分配一个值,然后在块外使用它。 我在遇到错误访问错误的块后引用NSString时尝试使用__block螺母。 我正在使用ARC就是这样。 例如:

__block NSString *str;

someBlock ^(id param1)
{
    str = @"iPhone";
}

[str getCharAtIndex:1]; //or w/e

我是在做概念上错误的事情,还是不允许这样做? 非常感谢您的帮助。

编辑:

这是实际的代码,基本上该代码将tweet作为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

也感谢你们的帮助

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

首先,只有在执行块之后, str才会被更新。 因此,除非您在该行使用了dispatch_sync ,否则在此行: [str getCharAtIndex:1]; 该块不太可能被执行,并且str不会被更新。

其次,如果您不使用ARC,则__block变量将不会自动被block对象保留。 这意味着,如果您不保留它,那么与访问strstr可能是已释放的对象,并且会使您的应用程序崩溃。

您只是在定义您的块而没有调用它。

尝试这个 :)

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM