本文介绍了Objective-C:类别中的属性/实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于无法在Objective-C的类别中创建综合属性,因此我不知道如何优化以下代码:

As I cannot create a synthesized property in a Category in Objective-C, I do not know how to optimize the following code:

@interface MyClass (Variant)
@property (nonatomic, strong) NSString *test;
@end

@implementation MyClass (Variant)

@dynamic test;

- (NSString *)test {
    NSString *res;
    //do a lot of stuff
    return res;
}

@end

在运行时多次调用 test-method ,我正在做很多工作来计算结果.通常,使用综合属性时,我会在第一次调用该方法时将值存储在IVar _test中,然后在下一次返回该IVar时.如何优化上面的代码?

The test-method is called multiple times on runtime and I'm doing a lot of stuff to calculate the result. Normally using a synthesized property I store the value in a IVar _test the first time the method is called, and just returning this IVar next time. How can I optimized the above code?

推荐答案

@lorean的方法将运行,但是您只需要有一个存储插槽.因此,如果您想在多个实例上使用它,并让每个实例计算一个不同的值,则它将无法正常工作.

@lorean's method will work , but you'd only have a single storage slot. So if you wanted to use this on multiple instances and have each instance compute a distinct value, it wouldn't work.

幸运的是,Objective-C运行时有一个叫做关联对象的东西,它可以准确地完成您的工作想要:

Fortunately, the Objective-C runtime has this thing called Associated Objects that can do exactly what you're wanting:

#import <objc/runtime.h>

static void *MyClassResultKey;
@implementation MyClass

- (NSString *)test {
  NSString *result = objc_getAssociatedObject(self, &MyClassResultKey);
  if (result == nil) {
    // do a lot of stuff
    result = ...;
    objc_setAssociatedObject(self, &MyClassResultKey, result, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  }
  return result;
}

@end

这篇关于Objective-C:类别中的属性/实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 08:08