ios - ViewController 的实例返回 nil

标签 ios objective-c

我有 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);
restaurantDataGlobalFunctions 中全部为零,如下所示类(class)。

enter image description here

最佳答案

从您分享的代码片段和屏幕截图中,我们可以清楚地看到您的实例已成功创建。

属性值显示为 nil,因为您没有为它们分配任何值。尝试为这些属性分配初始值。

对于与 UI 相关的属性,您应该将它们映射到 .xib 或 .storyboard 文件中,以便使用某些值对其进行初始化,或者在使用它们之前在代码中的某个位置对其进行初始化。

例如,在您的情况下:productCollectionView 和 categoryCollectionView

类似情况下的其他属性。

希望我的回答有帮助!

关于ios - ViewController 的实例返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43672488/

相关文章:

objective-c - 错误 : "Calls to mailbox_fql have exceeded the rate of 300 calls per 600 seconds"

ios - 如何在 Objective-C 中为 pin mapview 中的文本添加事件处理程序?

ios - Pod GoogleMaps无法运作

ios - UITableViewCell 标签没有更新

ios - 如果我只使用本地通知,是否需要为我的应用程序 ID 启用推送通知?

ios - 如何访问来自不同类 Obj-C 的变量

ios - 复杂行警告 : AnyObject is not a subtype of NSObject

javascript - iOS 忽略 Swiper 画廊的容器宽度

ios - 如何从url下载视频并将其保存到iOS中的文档目录?

架构 x86_64 的 IOS undefined symbol