调用不同类中的方法

时间:2014-10-02 02:07:45

标签: ios objective-c

我有一个子类UITableViewController的类。根据在此类中识别的用户操作,我需要在UIViewController中的表上调用一个表,该表是实例化的。我无法弄清楚如何做到这一点。

我尝试将函数设置为静态,但由于存在我需要访问的实例变量,因此无法工作。我可以使用NSNotificationCenter,但我的直觉是有更好的方法。有人可以帮忙吗?谢谢!

MonthsTableViewController.h

@interface MonthsTableViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate>
{
    NSArray *monthsArray;
}
@end

MonthsTableViewController.m

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSLog(@"calling the UIViewController");
    //this is where I am stuck!!!
}

SubscribeViewController.h

@interface SubscribeViewController : UIViewController <SIMChargeCardViewControllerDelegate>
{
    MonthsTableViewController *monthsController;
    IBOutlet UITableView *monthsTable;
}

- (void) snapMonthsToCenter;

@end

SubscribeViewController.m

- (void) snapMonthsToCenter {
    // snap the table selections to the center of the row
    NSLog(@"method called!");
    NSIndexPath *pathForMonthCenterCell = [monthsTable indexPathForRowAtPoint:CGPointMake(CGRectGetMidX(monthsTable.bounds), CGRectGetMidY(monthsTable.bounds))];
    [monthsTable scrollToRowAtIndexPath:pathForMonthCenterCell atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}

1 个答案:

答案 0 :(得分:0)

基本上,为了做到这一点,你需要从UITableViewController引用你的UIViewController。这将允许您调用此对象的方法。通常,您会将此属性称为delegate,因为您正在分配&#34;父母&#34; UIViewController作为&#34;孩子的代表&#34;的UITableViewController。

修改您的UITableViewController(MonthsTableViewController.h)以添加委托属性,如下所示:

@interface MonthsTableViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate>
{
    NSArray *monthsArray;
    id delegate;
}

@property (nonatomic, retain) id delegate;

@end

您需要@synthesize .m文件中的SubscribeViewController.h属性。如果您还没有,也可以在此标题中导入MonthsTableViewController

然后,当您实例化MonthsTableViewController时,请将委托设置为当前对象MonthsTableViewController *example = [[MonthsTableViewController alloc] init.... // This is the line you should already have [example setDelegate:self]; // Set this object's delegate property to the current object ,如下所示:

SubscribeViewController

现在,您可以访问MonthsTableViewController中的父respondsToSelector:。那你怎么称呼功能呢?简单!您可以对方法调用进行硬编码,或者为了超级安全,使用[(MonthsTableViewController*)[self delegate] snapMonthsToCenter];

if([[self delegate] respondsToSelector:@selector(snapMonthsToCenter)]) {
    [[self delegate] snapMonthsToCenter];
}

在你的情况下,上面的代码是绝对正常的,因为你知道这个方法将永远存在于这个对象上。但是,通常会将委托声明为可能具有可选方法的协议。这意味着尽管在@interface中声明了方法,但它们实际上可能并不存在(可以实现)在对象中。在这种情况下,将使用以下代码来确保可以在对象上实际调用该方法:

{{1}}
相关问题