我有 HomeViewController
的实例如下。我正在尝试访问其保存数据集的属性。但是,每当我签到其他类(class)时 - GlobalFunctions
所有HomeViewController
属性为零。
HomeViewController.h
@property (nonatomic, strong) NSMutableArray *pTempElements;
+(HomeViewController*) homeDataInstance;
HomeViewController.m
+(HomeViewController*) homeDataInstance {
static HomeViewController *dataInstance;
@synchronized(self) {
if(!dataInstance){
dataInstance = [[HomeViewController alloc] init];
}
}
return dataInstance;
}
-(void)loadFromURL {
NSString *path = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"plist"];
NSDictionary *settings = [[NSDictionary alloc] initWithContentsOfFile:path];
NSString *PRODUCT_ALL_URL = [settings objectForKey: @"PRODUCT_ALL_URL"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:PRODUCT_ALL_URL parameters:nil progress: nil success:^(NSURLSessionTask * _Nonnull operation, id responseObject) {
if(responseObject != NULL) {
ProductData *dicItem = [[ProductData alloc]init];
for ( id jsonItem in responseObject)
{
dicItem = [[ProductData alloc]initWithDictionary:jsonItem];
[self.pElements addObject:dicItem];
}
self.pTempElements = pElements;
[self.productCollectionView reloadData];
}
} failure:^(NSURLSessionTask * _Nullable operation, NSError * _Nonnull error) {
}];
}
GlobalFunctions.m
HomeViewController *restaurantData = [HomeViewController homeDataInstance];
// the following is nil
NSLog(@"%@", restaurantData.pTempElements);
restaurantData
在 GlobalFunctions
中全部为零,如下所示类(class)。最佳答案
从您分享的代码片段和屏幕截图中,我们可以清楚地看到您的实例已成功创建。
属性值显示为 nil,因为您没有为它们分配任何值。尝试为这些属性分配初始值。
对于与 UI 相关的属性,您应该将它们映射到 .xib 或 .storyboard 文件中,以便使用某些值对其进行初始化,或者在使用它们之前在代码中的某个位置对其进行初始化。
例如,在您的情况下:productCollectionView 和 categoryCollectionView
类似情况下的其他属性。
希望我的回答有帮助!
关于ios - ViewController 的实例返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43672488/