ios - 在类方法之间匹配 2 个 NSString 值

标签 ios objective-c class methods

我知道我无法在类方法中传递实例变量,因此我不再困惑两者之间的区别。

因此我有点卡住了。

我有 2 个类方法,它们都可以采用 NSString作为一个论点。

到底有没有办法可以匹配呢? 因为一个类方法有一个字符串,该字符串将是按下按钮后需要在 Safari 中打开的 url,因此 @selector(openBrowser:)需要知道来自JWKObjectView01的url是什么

请告诉我有办法做到这一点吗?

我尝试将其全部更改为实例方法,但是当我按下按钮时应用程序崩溃 - 所以我正在尝试解决这个问题:-)

提前致谢。 PS我知道我一开始就说我明白你不能混合这两个类 - 据我所知,但也许我错过了一些东西?

//添加代码:

UIView类 .h文件

@interface JWKObjectView01 : UIView <UIWebViewDelegate>
{
    NSString *string;
    NSURL *url;

    NSUserDefaults *defaults;
}

+ (JWKObjectView01 *)anyView:(UIView *)anyView
                         title:(NSString *)title
                        weburl:(NSString *)webstring;

+ (void)openBrowser:(NSString *)urlString;

.m文件

+ (JWKObjectView01 *)anyView:(UIView *)anyView
                       title:(NSString *)title
                      weburl:(NSString *)webString
{
    JWKObjectView01 *anotherView = [[JWKObjectView01 alloc] initWithFrame:CGRectMake(0,0,320,200)];
    anotherView.backgroundColor = [UIColor yellowColor];

    [anyView addSubview:anotherView];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(20, 20, 100, 100);

    [button setTitle:title forState:UIControlStateNormal];
    [button addTarget:self action:@selector(openBrowser:) forControlEvents:UIControlEventTouchUpInside];

    [anotherView addSubview:button];

    return anotherView;
}

+ (void)openBrowser:(NSString *)urlString;
{

    //This is where I am stuck and I need the variable - weburl:(NSString *)webString - 

    NSURL *url = [NSURL URLWithString:urlString];

    [[UIApplication sharedApplication] openURL:url];
}

.m 文件 View Controller

-(void)viewDidLoad
  {
     [JWKObjectView01 anyView:self.view title:@"OPEN" weburl:@"http://google.com"];
  }

最佳答案

对 url 使用静态变量。在 initialize 方法(不是 init 方法)中初始化它。您当然可以添加一个设置静态变量值的方法。

静态变量与其他语言中的类变量一样,在运行时仅存在一次。

但它们不是类变量。当该名称也用于其他类中的其他静态变量时,您可能会遇到命名冲突。因此,请熟悉单例模式,并在需要静态变量时考虑使用它。

有些人“滥用”应用程序委托(delegate)对象作为全局字符值的容器。这可能不是“书外的”,但效果很好并且很常见。 但是,我相信单例的情况要好得多。

所有这些都假设相关 URL 对于 JWKObjectView01 的所有实例一次携带相同的值。

关于ios - 在类方法之间匹配 2 个 NSString 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16080364/

相关文章:

class - Delphi:将数据存储在类与记录中,减少内存使用

ios - 无法使用(swift3 xcode9 iOS)解析标识符 socketmanager

ios - 在 swift 项目中使用 Wordpress ios 编辑器(用 objective-c 编写)

iphone - UITableView 部分出现不同的单元格颜色

ios - 无法获取tableView的contentOffset

iphone - 如何使用 MFMailComposerViewController 将 UIImage 添加到电子邮件中?

ios - 在我的应用程序中多次使用相同的代码

python - 运行 def __init__(self) 函数后,如何在类对象中添加数据?

javascript - 定义一个扩展 Function 的类

ios - Swift 中 XCode 中的计算器布局困难