在iOS中的方法外部访问实例变量值

时间:2013-08-14 06:31:56

标签: iphone ios objective-c

我有一个问题是重新访问方法外部的实例变量。我想在其他方法中访问该值。但是当我在其他方法中打印该值时,则打印空值。 所以,我需要你的帮助。如果你没有得到我的问题,请告诉我。 感谢

        //I am giving a snippet of my code
//DBForHomeViewController.h class
@interface DBForHomeViewController : UIViewController{
   id _jsonDB;
}
-(void)channelIDForDataBase;
-(void)openDataBase;

@end

//DBForHomeViewController.m class
@implementation DBForHomeViewController
-(void)channelIDForDataBase
{

   for (NSString *pNewString in stringValueOfCIdDB) {

      NSString *recentVideoUrl=[NSString stringWithFormat:@"%@%@",pNewString,fullPublishDate,];


        NSURL *videoUrlPublished=[NSURL URLWithString:recentVideoUrl];
        NSURLRequest *requestVideoUrlPublished=[NSURLRequest requestWithURL:videoUrlPublished];


        AFJSONRequestOperation *operationURL = [AFJSONRequestOperation JSONRequestOperationWithRequest:requestVideoUrlPublished success:^(NSURLRequest *requestURL, NSHTTPURLResponse *response, id getSTATS)
                                               {

                                                    _jsonDB= getSTATS;
                   //  NSLog(@"DB data is:%@",_jsonDB);
                   //I am getting json data here.Now I want to access _jsonDB in other                  //method ie -(void)openDataBase)                           
  }failure:nil];
                [operationURL start];
    }
 }

-(void)openDataBase

{
    NSLog(@"data in another class is :%@",_jsonDB);
  //here I am getting _jsonDB value as null
  //I want to to have _jsonDB value in this method
   //
}

3 个答案:

答案 0 :(得分:1)

您正在通过异步调用设置变量的值,因此调用可能尚未完成,并在您要求时设置变量。

您没有显示用于调用此变量的代码,但我怀疑您正在调用channelIDForDataBase然后调用openDataBase问题是因为第一个调用是异步的,它还没有完成它的网络通话所以没有设置ivar。

您有几个可能的解决方案:其中一个可能适合您的情况是在您的异步调用完成后拨打openDataBase

AFJSONRequestOperation *operationURL = [AFJSONRequestOperation JSONRequestOperationWithRequest:requestVideoUrlPublished success:^(NSURLRequest *requestURL, NSHTTPURLResponse *response, id getSTATS) {
    _jsonDB= getSTATS;
    [self openDataBase];

failure:nil];

答案 1 :(得分:0)

你将id _jsonDB指向getSTATS,之后,getSTATS被释放,实际上_jsonDB指向已被删除的内存空间。为_jsonDB创建了一个独立的内存空间,并将getSTATS的内容复制到其中。

这样做。

_jsonDB =[getSTATS copy];

答案 2 :(得分:-1)

我相信你的对象正在被释放。

这样做:

@interface DBForHomeViewController : UIViewController
@property (strong, nonatomic) id jsonDB;
@end

设置
self.jsonDB = getSTATS;