ios - 使用单例调用类方法中的实例方法

标签 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");
}

最佳答案

在 + 方法中你不能为那个目的使用 self,因为类方法中的 self 返回 Class 而不是实例。

替换

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

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

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

关于ios - 使用单例调用类方法中的实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20891885/

相关文章:

ios - 没有 KVC 的 RestKit 响应描述符映射

java - 多线程环境中跨整个应用程序的变量的单个实例

c - 顶点属性除数不适用于实例渲染

存储在 shelf 中的 Python 实例在关闭后发生变化

ios - xcode 构建失败,并从 : "_RCTSetLogFunction", o 引用 : -[AppTests testRendersWelcomeScreen] in AppTests.

c++ - 在 Objective-C 中使用外部 C++ 头文件

Iphone 谷歌地图 GPS 图标

java - JBoss中如何获取单例实例?

sql-server - SQL Server : how to constrain a table to contain a single row?

php - 如何在 Zend2 中访问另一个命名空间中的模型?