ios - 打破 Cocoa iOS 中 MVC 对象之间的循环依赖

标签 ios cocoa testing model-view-controller tdd

大家好堆垛机,

我正在尝试使用 TDD 在 iOS 应用程序中实现 MVC,但我不断获得模型和 Controller 之间以及 Controller 和 View 之间的循环依赖关系。我想紧密匹配图 1 中所示的 Cocoa MVC 模式。 Apple 文档的 7.2 ( https://developer.apple.com/library/ios/documentation/general/conceptual/CocoaEncyclopedia/Model-View-Controller/Model-View-Controller.html )。

问题源于我对初始化的 tdd 要求:所有 MVC 对象及其所有依赖项。我需要初始化所有依赖项,以便在测试期间可以替换模拟。这是我的问题的一个简单示例。

查看:

示例 View .h

//exampleView.h
#import <UIKit/UIKit.h>
#import "exampleViewController.h"

@interface exampleView : UIView

- (id)initWithFrame:(CGRect)frame andVC:(exampleViewController *)VC;

- (void) updateLabelText:(NSString *)newText;

@end

exampleView.m

//exampleView.m
#import "ExampleView.h"
#import "ExampleViewController.h"

@interface exampleView ()

@property (nonatomic) UILabel *label;
@property (nonatomic) UIButton *button;
@property (nonatomic) exampleViewController* VC;

@end

@implementation exampleView
// use your imagination...
@end

Controller :

//exampleViewController.h
#import <UIKit/UIKit.h>
#import "ExampleModel.h"
#import "ExampleRootView.h"

@interface ExampleViewController : UIViewController

- (id) initWithView:(exampleView *)view andModel:(ExampleModel*)model;

- (void) userActionButtonTapped();

@end

模型

//exampleModel.h
#import "exampleViewController.h"
@interface exampleModel : NSObject
-(id)initWithVC:(UIViewController *)VC;
//other model type stuff

@end

现在,当尝试初始化这些对象中的任何一个时,麻烦就来了。因为它们是循环依赖的,所以有点像先有鸡还是先有蛋的情况。

最佳答案

设计 MVC 系统的正常方法是让事物“向下”或“横向”依赖(例如, View 依赖于 Controller , Controller 依赖于模型,模型仅依赖于其他模型)。这在 Apple 的框架中被 View Controller 弄糊涂了一点,但仍然广泛适用。让模型依赖于 Controller 在这里很奇怪——为什么有必要这样做?听起来可能存在一些不必要的耦合。

关于ios - 打破 Cocoa iOS 中 MVC 对象之间的循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19105142/

相关文章:

testing - Vagrant 环境的自动化测试

iOS Pinterest 插入 nil 对象

ios - 使用绑定(bind)项目将 native 库 libxml2 链接到 xamarin.ios 项目

iphone - UIButton继承选择状态

objective-c - 如果标签包含 NSAttributed 字符串且部分字符串为粗体,如何获取标签的准确高度

iphone - 如何对文本进行自动换行?

cocoa - Twitter for Mac 在 Cocoa 应用程序中集成

python - 单元测试发现测试根目录时出现 ImportError

javascript - 用 jest 测试 React 中的异步方法

ios - swift 3 准备(用于 segue : ) function broken?