我在方法外访问实例变量时遇到问题。我想访问其他方法中的值。但是当我在其他方法中打印该值时,会打印空值。 伙计们,我需要你们的帮助。如果你们没有收到我的问题,请告诉我。 谢谢
//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
//
}
最佳答案
您正在通过异步调用设置变量的值,因此调用可能尚未完成并在您请求时设置变量。
你没有显示你用来调用这个变量的代码,但我怀疑你正在调用 channelIDForDataBase
然后调用 openDataBase
问题在于第一个调用是异步的,它还没有完成它的网络调用,所以还没有设置 ivar。
您有几个可能的解决方案:其中一个可能适合您的情况是在异步调用完成时调用 openDataBase
:
AFJSONRequestOperation *operationURL = [AFJSONRequestOperation JSONRequestOperationWithRequest:requestVideoUrlPublished success:^(NSURLRequest *requestURL, NSHTTPURLResponse *response, id getSTATS) {
_jsonDB= getSTATS;
[self openDataBase];
failure:nil];
关于iphone - 在 iOS 的方法之外访问实例变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18224702/