目标C的实例变量,为什么要声明它们? [英] Objective C's Instance Variables, why should I declare them?

查看:70
本文介绍了目标C的实例变量,为什么要声明它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解为什么我需要声明实例变量.让我解释一下我的意思.

I'm having a hard time understanding why I need to declare Instance Variables. Let me explain what I mean..

例如.

@interface LearningViewController : UIViewController {
  UILabel *myText; // <--- Instance Variables
}

@property (nonatomic,retain) IBOutlet UILabel *myText;

-(IBAction)method:(id)sender;

@end

这也可以通过

@interface LearningViewController : UIViewController {
  //instance variables go here, but are not declared, I just leave this field blank
}

@property (nonatomic,retain) IBOutlet UILabel *myText;

-(IBAction)method:(id)sender;

@end

如您所见..在后一个示例中,我仅为UILabel * myText

as you can see.. in the latter example I ONLY built the setter / getter for the UILabel *myText

,但在前者中,我也声明了实例变量.

but in the former I declared the Instance Variables too.

最终都可以正常工作

@implementation LearningViewController

@synthesize myText;


-(IBAction)method:(id)sender {
  [myText setText:@"hey"];

  //or

  NSString *myObject = [[NSString alloc]initWithString:@"hey"];

  [myText setText:myObject];    
}

现在,两种情况都产生相同的结果.所以我的问题是,为什么?两种方式做它们的好处是什么? 以及为什么我要构建和反对

now both things produce the same result. So my question is, why? and what are the benefits of doing them either way? And why would I build and object

NSString *myObject = [[NSString alloc]initWithString:@"hey"];

myText.text = myObject;

我什么时候可以做

[myText setText:@"hey"];

提前谢谢.

推荐答案

此外,有时您还想在一个类中使用受保护的或私有的iVar,而又不想从中构造属性. (例如,当您不想允许iVar访问除此类(私有)或其后代(受保护)的实例之外的任何内容时.标头中声明的属性可用于任何可以查看"该对象的对象从信息隐藏的角度来看,自动将标头中的ivars声明为属性(在花括号内带有或不带有声明)可能是不好的.

Also, there are times when you want to use a protected or private iVar within a class and not make a property out of it. (for example, when you don't want to allow access of an iVar to anything but an instance of this class (private) or its descendants (protected). Properties declared in the header are available to any object that can "see" the target object. Automatically declaring ivars in the header as properties (with or without the declaration inside the curly braces) might be bad from the standpoint of information hiding.

您还可以在.m文件中添加一个实现部分:您声明在那里的任何属性都将是该类的私有属性.好处(显然)是在需要的地方隐藏信息,以及使用点符号的能力.

You can also add an implementation section to your .m file: any properties you declare there will be private to the class. The benefit (obviously) is both in achieving information hiding where needed, and the ability to use the dot notation.

这篇关于目标C的实例变量,为什么要声明它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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