iphone - 实现 UIViewController 类别

标签 iphone objective-c ios cocoa-touch

我正在尝试在返回主实例的 MainContainerViewController 上实现一个类别:

在我的 .h 中:

@interface UIViewController(MainViewExtension)
/** Convience method for getting access to the MainContainerViewController instance */
- (MainContainerViewController *)mainContainerExtension;
@end

在我的.m
@implementation UIViewController(MainViewExtension)
- (MainContainerViewController *)mainContainerExtension
{
    return (MainContainerViewController *)self;
}
@end

所以从一些外部 View Controller ,我执行 self.mainContainerExtension 来访问实例,并且只声明了一个实例,但它没有给我正确的实例。
NSLog(@"number of children:%i", [self.mainContainerExtension.childViewControllers count]);

即使它应该是 3,它也会返回 0,所以我知道它没有给我正确的结果。我错过了什么吗?

编辑:我知道它没有给我正确实例的方式是因为在 viewDidLoadMainContainerViewController , 我有这个:
- (void)viewDidLoad
{
    appDelegate.notesViewController=[[NotesViewController alloc] init];
    appDelegate.notesViewController.mainContainer=self;
    [self addChildViewController: appDelegate.notesViewController];
}

每个NotesViewController具有 MainContainerViewController 类型的属性,这样我总有办法访问 MainContainerViewController来自 NotesViewControllers .但是我刚刚了解了类别和扩展,我认为只实现一个类别可能更容易,让我可以从我所在的任何 View 访问容器 View ,而不是在每个 View Controller 上都有一个属性。这是我的第一次,所以我确定我的类别实现有问题,只是不确定它是什么。

最佳答案

我不认为返回 self 的实例方法有用。无论您将在什么对象上调用它:[someVC mainContainerExtension],您都已经有了答案:它是 someVC。

如果每个 NotesViewController 都有一个包含 VC 的属性,那么你不是都准备好了吗?只要它在 NotesVC header 中是公开的:

MainContainerViewController *mainVC = [[MainContainerViewController] alloc] init ...];

// then, after the view loads
for (UIViewController *vc in mainVC.childViewControllers) {
  NSLog(@"%@", (NotesViewController *)vc.mainContainer);
}

另请注意,除非应用程序中只有一个 NotesViewController,否则在 appDelegate 中分配的那个将被覆盖。 appDelegate 中的句柄将是最后一个分配的句柄。

关于iphone - 实现 UIViewController 类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9860807/

相关文章:

ios - 使用 Swift 将数据写入自定义文件夹

iphone - 如何以编程方式将面包屑 View 添加到我的 UINavigationController 应用程序?

iphone - Objective C 中的 ~ 前缀

ios - 核心数据子查询谓词

objective-c - 通过交集和并集组合 NSArrays

iphone - 应用程序无法安装在 iPhone 上,但可以在模拟器上运行

iphone - 在 iOS 中使用 GCD

ios - 在 objective-c 中隐藏键盘

ios - 使 UITextView 多行

ios - 类似Apple Watch健身应用的渐变画环