无法访问iOS上的全局实例(由工厂构建)



这是我最后一个问题的后续问题:iOS:在应用程序启动时初始化对象,供所有控制器使用。

我已经将我的应用程序设置如下(忽略DB前缀):

DBFactoryClass     // Built a DataManaging Object for later use in the app
DBDataModel        // Is created by the factory, holds all data & access methods
DBViewControllerA  // Will show some of the data that DBDataModel holds
moreViewControllers that will need access to the same DBDataModel Object

我会一步一步地完成应用程序,然后在最后的中发布问题

AppDelegate.h

#import "DBFactoryClass.h"

AppDelegate.m

- (BOOL)...didFinishLaunching...
{
    DBFactoryClass *FACTORY = [[DBFactoryClass alloc ]init ];
    return YES;
}

DBFactoryClass.h

#import <Foundation/Foundation.h>
#import "DBDataModel.h"
@interface DBFactoryClass : NSObject
@property (strong) DBDataModel *DATAMODEL;
@end

DBFactoryM类

#import "DBFactoryClass.h"
@implementation DBFactoryClass
@synthesize DATAMODEL;
-(id)init{
    self = [super init];
    [self setDATAMODEL:[[DBDataModel alloc]init ]];
    return self;
}
@end

ViewControllerA.h

#import <UIKit/UIKit.h>
#import "DBDataModel.h"
@class DBDataModel;
@interface todayViewController : UIViewController
@property (strong)DBDataModel *DATAMODEL;
@property (weak, nonatomic) IBOutlet UILabel *testLabel;
@end

ViewControllerA.m

#import "todayViewController.h"
@implementation todayViewController 
@synthesize testLabel;
@synthesize DATAMODEL;
- (void)viewDidLoad
{
    todaySpentLabel.text = [[DATAMODEL test]stringValue];    // read testdata
}
@end

DBDataModel.h

#import <Foundation/Foundation.h>
@interface DBDataModel : NSObject
@property (nonatomic, retain) NSNumber* test;
@end

DBDataModel.m

#import "DBDataModel.h"
@implementation DBDataModel
@synthesize test;
-(id)init{
    test = [[NSNumber alloc]initWithInt:4];       // only a testvalue 
    return self;
}
@end

该应用程序构建良好,并启动,但标签保持空白。因此,要么对象不存在(但我想这会导致一条错误消息),要么我的设置出现了其他问题。有什么想法吗?

两个注释:

  1. 你问问题的方法很简单:每次遇到绊脚石,你都会问一个问题,如果答案不能立即奏效,你就会再问一个。你必须在问题调试和自己深入代码之间花费一些精力,否则你将永远依赖外部帮助。

  2. 请使用常用的编码样式。CCD_ 1是为宏保留的。

现在转到代码:

- (BOOL) …didFinishLaunching…
{
    DBFactoryClass *factory = [[DBFactoryClass alloc] init];
    return YES;
}

这只是创建一个DBFactoryClass的实例,然后将其丢弃。换句话说,这本质上是一个反对。根据上一个答案中的注释判断,您可以使用情节提要功能创建控制器。他们应该如何接收对数据模型的引用?引用不会神奇地出现,你必须把它分配到某个地方。

我不熟悉故事板功能。我的方法是使用单独的XIB文件创建视图控制器,然后可以在Factory类中创建控制器实例,并将所需的引用传递给模型。最后,应用程序代理将创建工厂,要求它组装主控制器,然后将其设置为窗口的根视图控制器。就像我的示例项目一样。有可能有一种方法可以让它与故事板配合使用,但正如我所说,我对它们并不熟悉。

最新更新