使用obj-c访问器和使用点语法有什么区别? [英] What's the difference between using obj-c accessors and using dot syntax?

查看:122
本文介绍了使用obj-c访问器和使用点语法有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自从我开始进行iPhone开发以来,我一直很困惑,哪种方式是以类中的成员身份访问数据的最佳方式。

Since I've started on iPhone development I've been kinda confused as to which is the best way to access data as a member in a Class.

让我们一起来说我有一个名为MyClass的类,其中包含:

Let's say I have a class called MyClass, and in it I have:

@interface MyClass : NSObject {
    int myInt;
}

@property (nonatomic, assign) int myInt;

在实施中,最好这样做:

In the implementation, is it better to do this:

myObject.myInt = 1;

还是这个?

[myObject setMyInt:1];

这也是读取价值。

int newInt = myObject.myInt;

vs。

int newInt = [myObject myInt];


推荐答案

这没关系,它们是一样的事情。点语法是一种方便你使用,我觉得它使你的代码更清晰。

It doesn't really matter, they are the same thing. The dot syntax is a convenience that's there for you to use, and I feel like it makes your code cleaner.

我发现使用点语法抛出的一种情况编译器发出的警告或错误,如果你有一个id对象,即使你知道它有这个属性。

The one case where I find that using the dot syntax throws warning or errors from the compiler is if you have have an id object, even if you know it has that property.

id someReturnedObject = [somethingObject someMysteryObjectAtIndex:5];
int aValue = 0;
aValue = someReturnedObject.value; // warning
aValue = [someReturnedObject value]; // will just do it

这篇关于使用obj-c访问器和使用点语法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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