我创建了一个名为 DBcontrols 的模型类,我正尝试在多个 View 中使用它。 (我仍在尝试在 iOS 上学习正确的 MVC 技术。)但是第二个 View TableVC 并没有涉及它。我很确定我的问题出在应用程序 Delegate 上,这里称为 dBAppDelegate.m:
#import "dBAppDelegate.h"
// Controller Class
#import "DBcontrols.h"
// View Classes
#import "enterView.h"
#import "listTableVC.h"
@implementation dBAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
enterView *firstViewController = (enterView *)[[navigationController viewControllers] objectAtIndex:0];
listTableVC *secondViewController = (listTableVC *)[[navigationController viewControllers] objectAtIndex:0];
DBcontrols *aDataController = [[DBcontrols alloc] init];
firstViewController.dataController = aDataController;
secondViewController.dataController = aDataController;
return YES;
}
enterView.h 和listTableVC.h 都有这段代码:
#import <UIKit/UIKit.h>
@class Contacts;
@class DBcontrols;
either: @interface enterView: UIViewController
or: @interface listTableVC: UITableViewController
@property (strong, nonatomic) DBcontrols *dataController;
. . .
@end
dataController 是在 enterView.m 和 listTableVC.m 中合成的
这是 Storyboard:
Contacts TableVC,listTableVC,从enterView 导航栏上的List 按钮Push 继续栏。
全部编译成功,但是在enterView中调用了DBcontrols方法,但在listTableVC中没有调用。例如,在 enterView 和 listTableVC 中,我都使用 countContacts 方法:
- (NSUInteger)countContacts {
nC = 0;
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK) {
NSString *querySQL = [NSString stringWithFormat: @"SELECT * FROM contacts"];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(_contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
nC++;
}
}
}
NSLog(@"%d contacts in dB.", nC );
return [self.masterContactList count];
}
当从 listTableVC 调用它时,它从不响应。
我做错了什么?
谢谢!
最佳答案
在 didFinishLaunchingWithOptions:
中,secondViewController
尚不存在。 Controller 是延迟创建的;也就是说,在需要时并且仅在从 firstViewController 开始转换时才需要。
在 Storyboard 上下文中,您通常使用“传递”值
- (void) prepareForSegue: (UIStoryboardSegue *) segue sender: (id) sender
{
enterView *source = segue.sourceViewController;
listTableVc *target = segue.destinationViewController;
target.dataController = source.dataController;
}
关于ios - 如何让多个 View 使用同一个 Controller 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17602532/