2012-02-26 37 views
-1

這是我最後一個的後續問題:iOS: Initialise object at start of application for all controllers to useiOS上無法訪問全局實例(由工廠構建)

我已經設置我的應用程序,如下所示(忽略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 

DBFactoryClass.m

#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

有兩點需要注意:

  1. 你擁有了一個試探性的方法來提出問題:每次你打的絆腳石,你問一個問題,如果回答不立即工作,你問一個又一個。您必須在調試問題和自行編寫代碼之間花費一些精力,否則您將永遠依賴外部幫助。

  2. 請使用通用的編碼風格。 CAPS保留給宏。

我們的代碼:

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

這只是簡單的創建DBFactoryClass的一個實例,然後它扔了出去。換句話說,它本質上是一個無操作。通過上一個答案中的評論來判斷,使用故事板功能創建控制器。他們應該如何接收對數據模型的引用?該參考不會由魔法顯示,您必須將其分配到某處。

我不熟悉故事板功能。我要做的方式是使用單獨的XIB文件創建視圖控制器,然後可以在Factory類中創建控制器實例,並將所需的引用傳遞給模型。最後,應用程序委託會創建工廠,請求它組裝主控制器,然後將其設置爲窗口的根視圖控制器。就像在我的sample project。有可能有一種方法可以使它與故事板一起工作,但正如我所說的,我並不熟悉它們。

+0

嗨 - 感謝您的建議 - 我會從頭開始,故事板似乎隱藏太多,我實際上看到了什麼事情:) – 2012-02-26 17:18:12

+0

一個即時通訊對不起一個非常老的電話和錯誤,我再次在我的筆記本電腦上修復它,不知何故,我無法切換從移動的投票。 – 2012-02-26 17:19:32

+0

我管理它=) 我寫了一個自己的tabbarcontroller,讓工廠創建所有的意見,並直接添加到他們所有的公共數據模型,然後將它們發送到tabbarcontroller。 一個非常小的問題:爲什麼你把@class放在示例項目中的一些文件中 - 我把它留在了外面,它工作得很好? – 2012-02-26 18:14:19