我对iOS和Objective-C以及整个MVC范式都是新手,我一直坚持以下几点:

我有一个充当数据输入表单的视图,我想让用户选择多个产品。产品列在另一个具有UITableViewController的视图中,我已启用多个选项。

如何将数据从一个视图传输到另一个视图?我会将UITableView上的选择保存在一个数组中,但如何将其传递回上一个数据输入表单视图,以便在提交表单时将其与其他数据一起保存到核心数据?

我在网上冲浪,看到一些人在应用程序委托中声明了一个数组。我读了一些关于单态的东西,但我不明白这些是什么,我读了关于创建数据模型的东西。

正确的执行方式是什么?我将如何执行?


当前回答

新闻视图控制器

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  [tbl_View deselectRowAtIndexPath:indexPath animated:YES];
  News *newsObj = [newstitleArr objectAtIndex:indexPath.row];
  NewsDetailViewController *newsDetailView = [[NewsDetailViewController alloc] initWithNibName:@"NewsDetailViewController" bundle:nil];

  newsDetailView.newsHeadlineStr = newsObj.newsHeadline;

  [self.navigationController pushViewController:newsDetailView animated:YES];
}

NewsDetailViewController.h

@interface NewsDetailViewController : UIViewController
@property(nonatomic,retain) NSString *newsHeadlineStr;
@end

NewsDetailViewController.m

@synthesize newsHeadlineStr;

其他回答

我找到了最简单、最优雅的版本,带有传递块。让我们将等待返回数据的视图控制器命名为“A”,将返回的视图控制器称为“B”。在本例中,我们希望获得两个值:第一个是Type1,第二个是Type2。

假设我们使用Storyboard,第一个控制器设置回调块,例如在segue准备期间:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.destinationViewController isKindOfClass:[BViewController class]])
    {
        BViewController *viewController = segue.destinationViewController;

        viewController.callback = ^(Type1 *value1, Type2 *value2) {
            // optionally, close B
            //[self.navigationController popViewControllerAnimated:YES];

            // let's do some action after with returned values
            action1(value1);
            action2(value2);
        };

    }
}

和“B”视图控制器应声明回调属性BViewController.h:

// it is important to use "copy"
@property (copy) void(^callback)(Type1 *value1, Type2 *value2);

在实现文件BViewController.m中,当我们有了所需的值以返回回调时,应该调用:

if (self.callback)
    self.callback(value1, value2);

需要记住的一点是,使用块通常需要管理强引用和弱引用,如这里所述

这里有一个更简单的方法。

只需使用全局变量。声明传递给下一个类所需的对象或变量。

例如,我们有两个类-类A和类B。

在类A中,通常包含:

#import "classA.h"

@interface classA()

@end

@implementation classA

-(void)viewDidLoad
{
    ...
}
-(void)didReceiveMemoryWarning
{
    ...
}

B类包含:

#import "classB.h"

@interface classB()

@end

@implementation classB

-(void)viewWillLoad
{
    ...
}
-(void)didReceiveMemoryWarning
{
    ...
}

现在,将第二个类classB导入classA:

#import "classA.h"
#import "classB.h"  // --- Import classB to classA.
@interface classA()

@end

@implementation classA

-(void)viewDidLoad
{
    ...
}
-(void)didReceiveMemoryWarning
{
    ...
}

现在我们有一座桥去二等B班。现在,要将变量或对象声明为全局变量,请在第一个类的.m文件中声明它,如下所示:

在A.h类中

#import "classA.h"
#import "classB.h"
@interface classA()

@end
NSString *temp;  // ---- Declare any object/variable as global.
@implementation classA

-(void)viewDidLoad
{
    ...
    temp=@"Hello";
    ...
}
-(void)didReceiveMemoryWarning
{
    ...
}

这里,对象temp是NSString类的全局对象。要访问任何类中的全局对象或变量,只需在第二个类中重新声明对象或变量。例如,如下所示:

在B.m类中

#import "classB.h"

@interface classB()

@end
extern NSString *temp;  //----use `extern` keyword for using the global object/variable in classB that was declared in classA.
@implementation classB

-(void)viewDidLoad
{
    ...
    LabeL.text=temp;
    ...
}
-(void)didReceiveMemoryWarning
{
    ...
}

现在,第二个类可以访问该值。易于理解的此方法可用于任意数量的类。

注:

您应该将第二个类的.h文件导入到第一个类。但不需要进口将第一类的.h文件转换为第二类。

记住那座桥。如果有一座桥,它应该可以从两边走。

我建议使用块/闭包和自定义构造函数。

假设您必须将字符串从FirstViewController传递到SecondViewController。

您的第一个视图控制器。

class FirstViewController : UIViewController {

    func moveToViewControllerB() {

        let second_screen = SecondViewController.screen(string: "DATA TO PASS", call_back: {
            [weak self] (updated_data) in
            ///This closure will be called by second view controller when it updates something
        })
        self.navigationController?.pushViewController(second_screen, animated: true)
    }


}

第二个视图控制器

class SecondViewController : UIViewController {

    var incoming_string : String?
    var call_back : ((String) -> Void)?

    class func screen(string: String?, call_back : ((String) -> Void)?) -> SecondViewController {

        let me = SecondViewController(nibName: String(describing: self), bundle: Bundle.main);
        me.incoming_string = string
        me.call_back = call_back
        return me
    }

    // Suppose its called when you have to update FirstViewController with new data.
    func updatedSomething() {

        //Executing block that is implemented/assigned by the FirstViewController.
        self.call_back?("UPDATED DATA")
    }

}

这是一个非常古老的答案,这是反模式的。请使用委托。不要使用这种方法!!

1.在第二个视图控制器中创建第一个视图控制器的实例,并使其属性@property(nonatomic,assign)。

2.分配此视图控制器的SecondviewController实例。

2.完成选择操作后,将阵列复制到第一个视图控制器。卸载第二个视图时,第一个视图将保存阵列数据。

嗯,我们有几种方法可以使用委派系统或使用故事板Segue:

使用setter和getter方法,如viewController.h@属性(保留,非原子)NSString*str;现在,在viewController.m中@合成str;这里我有一个PDF URL和一个segue到另一个viewController,像这样,pdfObject是我的pdfModel。它基本上是一个NSOBJECT类。str=[NSString stringWithFormat:@“%@”,pdfObject.objPath];NSLog(@“pdfUrl:***:%@:***:”,pdfUrl);[self-performSegueWithIdentifier:@“programPDFViewController_segue”sender:self];#pragma标记-导航//在基于情节提要的应用程序中,您通常需要在导航之前做一些准备-(void)准备segue:(UIStoryboardSegue*)segue发件人:(id)发件人{if([[segue identifier]isEqualToString:@“programPDFViewController_segue”]){programPDFViewController*pdfVC=[segue destinationViewController];[pdfVC setRecivedPdfUrl:str];}}现在,我成功地接收了我的PDF URL字符串和其他ViewController,并在webview中使用该字符串。。。在处理这样的委托时,我有一个NSObject实用程序类,其中包含我的dateFormatter、sharedInstance、EscapeWhiteSpaceCharacters、convertImageToGrayScale等方法,以及我在整个应用程序中使用过的其他方法,现在在文件实用程序中使用。在这种情况下,您不需要在每次将数据从一个视图控制器解析到另一个视图时都创建变量。有一次,您在fileutility.h中创建了一个字符串变量。只需将其设为零并再次使用。@接口实用程序:NSObject文件实用程序.h:+(实用程序*)共享实例;@属性(非原子,保留)NSString*strUrl;现在在文件实用程序.m中:@实施实用程序+(实用程序*)共享实例{静态实用程序*sharedObj=nil;如果(sharedObj==nil){sharedObj=[[utilities alloc]init];}返回sharedObj;}现在完成了,请访问文件firstViewController.m并调用委托NSString*str=[NSString stringWithFormat:@“%@”,pdfObject.objPath];[连接共享实例].strUrl=nil;[连接共享实例].strUrl=str;现在直接转到文件secondViewController.m,在不创建变量的情况下使用它我所做的一切:-(无效)视图将出现:(BOOL)动画{[超级视图将出现:是];[self-webViewMethod:[Connection sharedInstance].strUrl];}-(void)WebViewMethod:(NSString)Url{//使用webview。享受编码:D}

这种委托工作在内存管理方面是可靠的。