Objective c 我们可以在公共文件中声明@properties吗
我有一个要求,我在协议中只有很少的只读属性,并将该协议应用于两个类(如a和B),因为这些属性是只读的,我在我的两个类a和B的.m文件中重新声明它们。我可以如何避免这两个类中所有属性的重复重新声明 创建一个类并在该类中声明只读属性。然后创建从类继承的类A和类B 你的CommonClass.h看起来像这样Objective c 我们可以在公共文件中声明@properties吗,objective-c,properties,protocols,readonly,Objective C,Properties,Protocols,Readonly,我有一个要求,我在协议中只有很少的只读属性,并将该协议应用于两个类(如a和B),因为这些属性是只读的,我在我的两个类a和B的.m文件中重新声明它们。我可以如何避免这两个类中所有属性的重复重新声明 创建一个类并在该类中声明只读属性。然后创建从类继承的类A和类B 你的CommonClass.h看起来像这样 #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface CommonClass : NS
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface CommonClass : NSObject
@property (strong, readonly) <Type1> property1;
@property (strong, readonly) <Type2> property2;
@end
您可以将公共特性定义放置到头文件中,并将其包含在每个类的接口中 公共标题:公共道具
@property (nonatomic, retain) SomeType *common1;
@property (nonatomic, retain) SomeType *common2;
@property (nonatomic, retain) SomeType *common3;
执行:上午
对B类重复上述步骤
不建议采用这种方法。反正是我干的。这样做有什么好处?任何减少行数的好处都会被增加的复杂性所抵消。是的,您可以在NSObject文件中声明它们。然后包括需要使用这些属性的头文件。您也可以对函数执行同样的操作。@Droppy,更少的行会降低复杂性,而不是增加复杂性。@WasimSafdar Thanx对于您的重播,如果我这样做,我将如何访问变量?我无法访问A.Var或B.Var rt?在定义协议时,可以在这两个类中采用该协议。甚至可以访问该协议中的变量并在类中更改它们。那么你就不需要在类中声明变量了。这否定了在协议中声明变量的好处。
@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