什么是 C# 中公共获取/保护集属性的 Objective-C 等价物 [英] What is the Objective-C equivalent of a public get/protected set property in C#

查看:22
本文介绍了什么是 C# 中公共获取/保护集属性的 Objective-C 等价物的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在Objective-C中创建一个像这个C#属性这样的属性?

Is there any way to create a property like this C# property in Objective-C?

public int prop { get; protected set;}

本质上,我想让从类外部获取值成为可能,但只能从类内部设置值.

Essentially, I want to make it possible to get the value from outside the class, but to only be able to set the value from within the class.

推荐答案

最简单的方法是在 MyClass 的公共接口中将属性声明为 readonly(即 .h 文件):

The easiest way to accomplish this is to declare the property as readonly in the public interface for MyClass (i.e. the .h file):

@property (readonly) NSInteger prop;

然后,在该类的 .m 文件中,声明一个类 extension(名称为空的类别).在类扩展中,您可以 重新声明@property 以将其可写性更改为可读写:

Then, in .m file for that class, declare a class extension (a category with an empty name). In class extensions, you may redeclare a @property to change its writeability to readwrite:

@interface MyClass ()
@property (readwrite) NSInteger prop;
@end

@implementation MyClass
@synthesize prop;
...
@end

当然,Objective-C 并没有强制执行访问限制,所以没有什么可以阻止一些流氓代码调用 -[MyClass setProp:].然而,编译器会将其标记为警告,这与您在 Objective-C 中所能获得的一样好.不幸的是,没有标准的方法可以将这个受保护的"可写属性记录到子类中;您必须为您的团队确定一个约定,或者如果它在您要发布的框架中,则将其放入课程的公共文档中.

Of course, Objective-C does not enforce access restrictions, so there's nothing stopping some rogue code from calling -[MyClass setProp:]. The compiler will flag this as a warning, however, which is as good as you can get in Objective-C. Unfortunately, there is no standard way to document this "protected" writeable property to subclasses; you'll have to settle on a convention for your team and or put it in the public documentation for the class if it's in a framework that you're going to release.

这篇关于什么是 C# 中公共获取/保护集属性的 Objective-C 等价物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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