我正在尝试执行一些非常简单的操作:
我有一个主页 View Controller 和一个支持删除单元格的 TableView Controller (单独的 Controller )。
在主页中,我有一个 UILabel 对象,我想用 TableView Controller 中的第一个单元格填充它。所以我想我需要的是在我的主页 View Controller 中创建我的 TableView Controller 的实例并询问此信息......但是由于某种原因我从名为“currentTarget”的 TableView Controller 中获取的对象是零...(事实并非如此)。
这是我的 HomeViewController:(只是相关的行)
#import "StackTableViewController.h"
@interface HomeViewController ()
@property (strong, nonatomic) IBOutlet UILabel *homeLabel;
@end
@implementation HomeViewController
- (id)init {
self = [super initWithNibName:@"HomeViewController" bundle:nil];
if (self) {
// Do something
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
[self.navigationController setNavigationBarHidden:YES];
self.homeLabel.font = [UIFont fontWithName:@"Candara-Bold" size:40];
StackTableViewController *svc = [[StackTableViewController alloc] init];
self.homeLabel.text = svc.currentTarget;
}
这是我的 StackTableViewController.m:(只是相关行)
#import "StackTableViewController.h"
#import "Target.h"
#import "StackTableViewCell.h"
#import "HomeViewController.h"
#import "CoreDataStack.h"
@interface StackTableViewController () <NSFetchedResultsControllerDelegate>
@property (nonatomic, strong) NSFetchedResultsController *fetchedResultController;
@end
@implementation StackTableViewController
- (id)init {
self = [super initWithNibName:@"StackTableViewController" bundle:nil];
if (self) {
// Do something
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
[self.fetchedResultController performFetch:nil];
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
Target *current = [self.fetchedResultController objectAtIndexPath:indexPath];
self.currentTarget = current.body;
}
并且还在 prepare for segue 方法中添加了这段代码,因此 currentTarget 将从 segue 返回时得到更新:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
[self.fetchedResultController performFetch:nil];
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
Target *current = [self.fetchedResultController objectAtIndexPath:indexPath];
self.currentTarget = current.body;
}
为什么我的标签不会显示 :/?
提前发送
最佳答案
问题是您的 init 方法没有初始化获取的结果 Controller 或 currentTarget 属性。它们仅在您呈现该 TableView Controller 并且 viewDidLoad 方法运行时才被初始化。如果您将这些行移动(或复制)到您的 init 方法,它应该可以工作:
[self.fetchedResultController performFetch:nil];
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
Target *current = [self.fetchedResultController objectAtIndexPath:indexPath];
self.currentTarget = current.body;
关于ios - 无法从另一个 View Controller 获取 TableView 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27589250/