从类方法访问属性? [英] Access property from a class method?

查看:68
本文介绍了从类方法访问属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了使我的代码可测试,我创建了一个惰性初始化器;这样在我的单元测试中,我可以在调用 getter 之前模拟我想要的任何对象.

但是,当涉及到类方法时,我的类方法无法访问我定义的属性.

  1. 有没有办法让我的类方法可以访问这些属性?
  2. 如果没有,是否有任何方法可以创建在此类外部也可访问的静态变量,即可由我的单元测试类访问?

<预><代码>@执行@synthesize webService;+ (void)doSomething{self.webService.url = @"some url";[self.webService 启动];//做其他事情}- (WebService*)webService{如果 (!webService){webService = [[WebService alloc] init];}返回网络服务;}@结尾

解决方案

看起来你需要一个单例.

<...>

更新:如果这种方式不可接受,以下是您问题的直接答案:

<块引用>

有什么办法可以让我的班级可以访问的属性方法?

没有.您必须以某种方式创建一个实例.

<块引用>

如果没有有什么方法可以创建统计变量也是可以在这个类之外访问?(可通过我的单元测试类访问

是的.您可以创建将保留实例的静态或全局变量.它们可以从您的课堂之外访问.静态变量在定义它的源文件中是可访问的;并且可以从任何地方访问全局变量.如果你想处理全局变量,你在 *.m 文件中定义它

MyClass *my_inst;

然后在 *.h 文件中进行声明:

external MyClass *my_inst;

In order to make my code testable, I have created a lazy initializer; this way in my unit test, I can mock any object I want before the getter gets called.

When it comes to class methods, though, my class method doesn't have access to the properties I have defined.

  1. Is there any way to make the properties accessible by my class method?
  2. If not, is there any way to create static variables that are also accessible outside of this class, i.e., accessible by my unit test class?


@implementation
@synthesize webService;

+ (void)doSomething
{
   self.webService.url = @"some url";
   [self.webService start];
   // do other things
}

- (WebService*)webService
{
   if (!webService)
   {
      webService = [[WebService alloc] init];
   }
   return webService;
}

@end

解决方案

Looks like you need a singleton.

<...>

Upd: If this way isn't acceptable, here are direct answers to your questions:

Is there any way to make the properties accessible by my class method?

No. You have to create an instance in some way.

If not is there any way to create statis variables that are also accessible outside of this class? (Accessible by my unit test class

Yes. You can create static or global variables that will keep instances. They will be accesible from outside your class. Static variable is accesible within the source file where it is defined; and global variable is accessible from everywhere. If you wand to deal with global variable, you define it in your *.m file

MyClass *my_inst;

and you make declaration in *.h file:

external MyClass *my_inst;

这篇关于从类方法访问属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆