【问题标题】:Can we declare @properties in a common file我们可以在公共文件中声明@properties
【发布时间】:2016-11-23 12:29:36
【问题描述】:

我有一个要求,我在协议中几乎没有 readonly 属性,并将该协议应用于两个类(比如 A 和 B),因为属性是 readonly,我在 .m Files 中重新声明它们我的两个类(A 和 B)我可以如何避免这两个类中所有属性的重复重新声明?

【问题讨论】:

  • 这样做有什么好处?减少行数的任何好处都会被复杂性的增加所抵消。
  • 是的,你可以在 NSObject 文件中声明它们。然后在需要使用这些属性的地方包含头文件。你可以对函数做同样的事情。
  • @Droppy,更少的行会降低复杂性而不是增加。
  • @WasimSafdar 感谢您的重播,如果我这样做,我将如何访问变量?我无法访问它 A.Var 或 B.var rt?
  • 在定义协议时,您可以在两个类中采用该协议。即使您访问该协议中的变量并在类中更改它们。那么你就不需要在类中声明变量了。

标签: objective-c properties protocols readonly


【解决方案1】:

创建一个类并在该类中声明您的只读属性。然后创建从该类继承的类 A 和 B。

所以你的CommonClass.h 看起来像这样

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface CommonClass : NSObject

@property (strong, readonly) <Type1> property1;
@property (strong, readonly) <Type2> property2;

@end

现在您可以创建继承自 CommonClass 的类 A 和 B

@interface A : CommonClass
 @interface B : CommonClass

【讨论】:

  • 这否定了在协议中声明它们的好处。
【解决方案2】:

您可以将公共属性定义放入头文件中,并将其包含在每个类的接口中。

通用头文件: common-props.h

@property (nonatomic, retain) SomeType *common1;
@property (nonatomic, retain) SomeType *common2;
@property (nonatomic, retain) SomeType *common3;

实施:上午

@interface A ()

// Note: you have to use include, not import,
// to ensure the contents will be interpolated, no matter what.
#include "common-props.h"

@end

@implementation A

    // Stuff

@end

对 B 类重复。

不推荐这种方法。反正由我来。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-14
    • 2018-11-12
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多