我对iOS和Objective-C以及整个MVC范式都是新手,我一直坚持以下几点:
我有一个充当数据输入表单的视图,我想让用户选择多个产品。产品列在另一个具有UITableViewController的视图中,我已启用多个选项。
如何将数据从一个视图传输到另一个视图?我会将UITableView上的选择保存在一个数组中,但如何将其传递回上一个数据输入表单视图,以便在提交表单时将其与其他数据一起保存到核心数据?
我在网上冲浪,看到一些人在应用程序委托中声明了一个数组。我读了一些关于单态的东西,但我不明白这些是什么,我读了关于创建数据模型的东西。
正确的执行方式是什么?我将如何执行?
如果要将数据从一个控制器传递到另一个控制器,请尝试以下代码:
文件FirstViewController.h
@property (nonatomic, retain) NSString *str;
SecondViewController.h
@property (nonatomic, retain) NSString *str1;
文件FirstViewController.m
- (void)viewDidLoad
{
// Message for the second SecondViewController
self.str = @"text message";
[super viewDidLoad];
}
-(IBAction)ButtonClicked
{
SecondViewController *secondViewController = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
secondViewController.str1 = str;
[self.navigationController pushViewController:secondViewController animated:YES];
}
在Swift中传递数据有很多解决方案。
向前传递数据
我最喜欢的两种转发数据的方式是依赖注入(DI)和属性观察者
依赖注入
class CustomView : UIView {
init(_ with model : Model) {
// Do what you want with data
}
}
财产观察员
class CustomView : UIView {
var model : Model? {
didSet {
// Do what you want with data after assign data to model
}
willSet {
// Do what you want with data before assign data to model
}
}
}
向后传递数据
还喜欢将数据传递到上一个VC/视图的方法:
协议和代表
protocol CustomViewDelegate : class {
func addItemViewController(_ with data: Model?)
}
weak var delegate : CustomViewDelegate?
class AnotherCustomView: UIView {
let customView = AnotherCustomView()
init() {
customView.delegate = self
}
}
extention AnotherCustomView : CustomViewDelegate {
func addItemViewController(_ with data: Model?) {
// Do what you want with data
}
}
关闭
class AnotherCustomView : UIView {
init(addItem: @escaping (_ value : Model?) -> ()) {
// Do what you want with data
}
}
class CustomView : UIView {
init() {
let customView = AnotherCustomView { [weak self] model in
// Do what you want with data
}
}
}
我更喜欢在没有代表和片段的情况下进行。它可以通过自定义init或设置可选值来完成。
1.自定义初始化
class ViewControllerA: UIViewController {
func openViewControllerB() {
let viewController = ViewControllerB(string: "Blabla", completionClosure: { success in
print(success)
})
navigationController?.pushViewController(animated: true)
}
}
class ViewControllerB: UIViewController {
private let completionClosure: ((Bool) -> Void)
init(string: String, completionClosure: ((Bool) -> Void)) {
self.completionClosure = completionClosure
super.init(nibName: nil, bundle: nil)
title = string
}
func finishWork() {
completionClosure()
}
}
2.可选变量
class ViewControllerA: UIViewController {
func openViewControllerB() {
let viewController = ViewControllerB()
viewController.string = "Blabla"
viewController.completionClosure = { success in
print(success)
}
navigationController?.pushViewController(animated: true)
}
}
class ViewControllerB: UIViewController {
var string: String? {
didSet {
title = string
}
}
var completionClosure: ((Bool) -> Void)?
func finishWork() {
completionClosure?()
}
}