【问题标题】:Can not call class method不能调用类方法
【发布时间】:2013-04-19 04:44:24
【问题描述】:

我正在构建一个基于标签的应用程序,并希望从每个选项卡 (ViewController) 调用相同的函数。

我正在尝试通过以下方式进行操作:

#import "optionsMenu.h"

- (IBAction) optionsButton:(id)sender{
   UIView *optionsView = [options showOptions:4];
   NSLog(@"options view tag %d", optionsView.tag);
}

optionsMenu.h文件:

#import <UIKit/UIKit.h>

@interface optionsMenu : UIView

- (UIView*) showOptions: (NSInteger) tabNumber;

@end

optionsMenu.m文件:

@import "optionsMenu.h"
@implementation optionsMenu

- (UIView*) showOptions:(NSInteger) tabNumber{
   NSLog(@"show options called");

   UIView* optionsView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
   optionsView.opaque = NO;
   optionsView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5f];
   //creating several buttons on optionsView
   optionsView.tag = 100;

return optionsView;

}

@end

结果是我从未收到“显示选项调用”调试消息,因此optionsView.tag 始终是0

我做错了什么?

我知道这很可能是一个简单而愚蠢的问题,但我自己无法解决。

感谢任何反馈。

【问题讨论】:

  • 我猜这是Objective-C。下次,请用适当的语言标记您的问题。
  • options 是否正确初始化?
  • 刚刚声明为 optionsMenu* options;
  • 你必须告诉我们你在哪里实例化“选项”。顺便说一下,按照惯例,类名应该以大写字母开头,即“OptionsMenu”而不是“optionsMenu”
  • 只需将您的方法类型更改为Class 方法,只需将- 替换为+ 即可。

标签: objective-c class methods


【解决方案1】:

首先要注意的是,这是一个实例方法(而不是问题标题中描述的 Class 方法)。这意味着为了调用此方法,您应该分配/初始化您的类的实例并将消息发送到实例。例如:

// Also note here that Class names (by convention) begin with
// an uppercase letter, so OptionsMenu should be preffered
optionsMenu *options = [[optionsMenu alloc] init];
UIView *optionsView = [options showOptions:4];

现在,如果您只想创建一个返回预配置 UIView 的 Class 方法,您可以尝试这样的事情(前提是您不需要在您的方法中访问 ivars):

// In your header file
+ (UIView *)showOptions:(NSInteger)tabNumber;

// In your implementation file
+ (UIView *)showOptions:(NSInteger)tabNumber{
    NSLog(@"show options called");

    UIView *optionsView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    optionsView.opaque = NO;
    optionsView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5f];
    //creating several buttons on optionsView
    optionsView.tag = 100;

    return optionsView;
}

最后像这样发送消息:

UIView *optionsView = [optionsMenu showOptions:4]; //Sending message to Class here

最后当然不要忘记将您的视图添加为子视图以显示它。 我希望这是有道理的......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 2023-04-11
    • 2017-04-23
    • 1970-01-01
    • 2019-11-15
    相关资源
    最近更新 更多