ios - 在另一个类中向 TableView 添加数据

标签 ios objective-c

我有一个 TableView,它是 HomeViewController 我还有另一个 View ,它是 NewViewController

在 HomeViewController 中,我可以通过执行以下操作将项目添加到 plist,例如“书名”键:

NSString *bookTitle;

self.books addObject:bookTitle

然后单击按钮以推送到有文本字段的 NewViewController。单击保存按钮时,我需要将 textField 的文本添加到 plist 中的 TableView “Book text”键

但是我不能在这个类中做 self.books,所以我怎样才能从 NewViewController 添加到 HomeViewController 中的 tableview

最佳答案

在 NewViewController 中定义一个委托(delegate)方法,单击按钮时调用该方法,将 textField 内容传递给 HomeViewController。 HomeViewController 实现委托(delegate)方法,然后可以根据需要更新书籍集合。例如:

NewViewController.h

// Define the delegate method(s)
@protocol NewViewControllerDelegate <NSObject>

-(void)addedTitle:(NSString *)text;

@end

@interface NewViewController : UIViewController

// Declare the delegate property
@property (nonatomic, weak)id <NewViewControllerDelegate>delegate;

// other declarations...

@end

NewViewController.m

#import "NewViewController.h"

@interface NewViewController ()

@end

@implementation NewViewController

// other implementation code...

-(IBAction)buttonTapped:(id)sender{
    [self.delegate addedTitle:textField.text];
}

@end

HomeViewController.h

#import <UIKit/UIKit.h>
#import "NewViewController.h"

// Note <NewViewControllerDelegate> on next line
@interface HomeViewController : UIViewController <NewViewControllerDelegate>

// other declaration code...

@end

HomeViewController.m

#import "HomeViewController.h"

@interface HomeViewController ()

@end

@implementation HomeViewController

-(void)viewDidLoad{
    [super viewDidLoad];

    myNewViewController.delegate = self;
}

// other implementation code...

#pragma mark - NewViewController delegate methods
// Implements the delegate callback
-(void)addedTitle:(NSString *)title{
    [self.books addObject:title];
}

@end

关于ios - 在另一个类中向 TableView 添加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20031325/

相关文章:

ios - 如何在不打开应用程序的情况下通过 Siri 显示 api 的响应?

ios - 类型 'UITouch' 的值没有成员 'locationInNode'

ios - Splunk 薄荷 : Failed to archive dSYMs for "MyApp" to "/tmp/splunk-mint-dsyms"

ios - 如何使用 NSManagedObjectContext 进行条件请求?

objective-c - 使用 Interface Builder 嵌套自定义类/XIB

iOS objective-c 从服务器 NSUrl 检索数据无法访问全局变量

ios - 为什么 'Pie Slice' 中的斜线无法使用 UIBezierPath 正确绘制?

ios - 在 iOS 中更新资源的简单方法(无需编译)

ios - 如何通过文件夹ios从 Assets 中获取图像

ios - 不会为小距离位置更改调用 didUpdateLocations 委托(delegate)方法