声明私有成员变量 [英] Declaring private member variables

查看:138
本文介绍了声明私有成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几周前我开始学习Objective-C,但我仍然不明白如何正确地管理类的封装。在类中声明私有成员变量的最佳方法是什么?

I've started learning Objective-C a few weeks ago and I still don't understand how to manage the encapsulation of a class correctly. What is the best way to declare a private member variable in a class?

似乎用@property为你的成员变量设置正确的getter / setter是正确的方法,不仅仅是在界面中声明它@private。但在我看来,这仍然让其他类可以访问这些变量。即使你声明属性readonly,外部类也可以访问成员变量的引用并修改它!

It seems that setting the right getter/setter for your member variable with "@property" is the right way to go, more than just declaring it "@private" in the interface. But it seems to me that this still gives other classes an access to these variables. Even if you declare the property "readonly", an outside class can access the reference to the member variable and modify it!

所以我猜测最好的声明方式私有成员变量是不通过声明属性而不包括任何guetter / setter。我对吗?或者有更好的方法吗?

So I'm guessing the best way to declare a private member variable is to not include any guetter/setter by not declaring a property. Am i right? Or is there a better way?

谢谢

推荐答案

如果你不希望它可供其他类访问,在您的实现上声明@property,为您的类创建一个匿名类别。

if you don't want it accessible to other classes, declare the @property on your implementation, creating an anonymous category for your class.

头文件:

// MyClass.h
@interface MyClass : NSObject {
    NSObject *_privateObject;
    NSObject *_readonlyObject;
    NSObject *_publicObject;
}

@property (nonatomic, retain, readonly) NSObject *readonlyObject;
@property (nonatomic, retain) NSObject *publicObject;

@end

实施:

// MyClass.m
@interface MyClass ()
    @property (nonatomic, retain) NSObject *privateObject;
    // Make it writable on the implementation
    @property (nonatomic, retain, readwrite) NSObject *readonlyObject;
@end

@implementation MyClass

@synthesize privateObject = _privateObject;
@synthesize readonlyObject = _readonlyObject;
@synthesize publicObject = _publicObject;

这些是三种不同属性的示例。

These are examples of three different properties.


  • privateObject 在其他类上不可见;

  • readonlyObject 可见但是只读;

  • publicObject 可见,可以获取和设置;

  • privateObject is not visible on other classes;
  • readonlyObject is visible but is read only;
  • publicObject is visible and can be get and set;

这篇关于声明私有成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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