简体   繁体   English

iOS如何实现协议的@property

[英]iOS how to implement a protocol's @property

What I understand is that a protocol specify method names, and someone else who conforms to that protocol do the implementation of the methods. 我理解的是协议指定方法名称,并且符合该协议的其他人执行方法的实现。

So what about the properties declared in a protocol? 那么协议中声明的属性呢? Is that to implement a property means to implement its setter and getter? 实现属性是否意味着实现其setter和getter?

Property is a fancy name for one or two methods with specific signatures for which Objective-C provides a convention that lets you call them using the alternative dot . 属性是具有特定签名的一个或两个方法的奇特名称,Objective-C提供了一种约定,允许您使用备用点调用它们. syntax. 句法。 There is no difference between a protocol declaring, say, a pair of 一个协议声明,例如,一对,没有区别

-(int) foo;
-(void)setFoo:(int)_foo;

methods, and a protocol declaring a read-write property: 方法和声明读写属性的协议:

 @property (readwrite) foo;

So you are absolutely right, implementing a property means implementing one or two methods, depending on whether you implement a read-only, write-only, or a read-write property. 所以你是绝对正确的,实现一个属性意味着实现一个或两个方法,具体取决于你是实现只读,只写还是读写属性。

As the others said, you just have to implements the getter and or setter (depending on the property). 正如其他人所说,你只需要实现getter和/或setter(取决于属性)。

I would add that you can just synthesize them : 我想补充一点,你可以合成它们:

@property (nonatomic, retain) NSObject * foo; @property(非原子,保留)NSObject * foo;

would end up in : 最终会:

@synthesize foo; @synthesize foo;

A protocol is just something that's makes sure that an object implements a set of methods. 协议只是确保对象实现一组方法的东西。 If you were to use an object as a delegate of your class for example, you would want to make sure that it implemented the methods that you're going to call. 例如,如果您要将对象用作类的委托,则需要确保它实现了您要调用的方法。 That's the point of a protocol. 这是协议的重点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM