使用Singleton在类方法中调用实例方法

时间:2014-01-02 21:06:57

标签: ios singleton instance class-method

我已经阅读过关于在类方法中调用实例方法是Singleton的最佳方法。

我尝试过但它没有用。我试图在@selector()中调用void方法,但我无法做到。请问我的问题在哪里?

·H

+ (void)normalizeCell:(UITableViewCell *)cell withLables:(NSArray *)lbls sx:(CGFloat)sx widths:(NSArray *)widths;
- (void)edit;

.M

+ (void)normalizeCell:(UITableViewCell *)cell withLables:(NSArray *)lbls sx:(CGFloat)sx widths:(NSArray *)widths
{

    static PozisyonOzetiTableCell *sharedMyManager = nil;
static BOOL initialized = NO;

if(!initialized)
{
    initialized = YES;
    sharedMyManager = [[PozisyonOzetiTableCell alloc] init];
}
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

//// I have tried edit & [sharedMyManager edit]
[button addTarget:self action:@selector(edit) forControlEvents:UIControlEventTouchUpInside];

[button setImage:[UIImage imageNamed:@"settingKey.png"] forState:UIControlStateNormal];
button.frame = CGRectMake(-23, 0, 70, 40);
[cell.contentView addSubview:button];
}

- (void)edit
{
    NSLog(@"CLICKED");
}

1 个答案:

答案 0 :(得分:2)

在+方法中,您不能将self用于该puspose,因为类方法中的self返回Class而不是实例。

替换

[button addTarget:self action:@selector(edit) forControlEvents:UIControlEventTouchUpInside];

[button addTarget:sharedMyManager action:@selector(edit) forControlEvents:UIControlEventTouchUpInside];

当然,如果你的sharedMyManager是静态字段。 并确保在调用该方法之前已初始化了您的sharedMyManager。