目标C强调财产与自我 [英] objective C underscore property vs self

查看:103
本文介绍了目标C强调财产与自我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用在Xcode中选择拆分视图应用程序时创建的标准示例拆分视图,并且在添加了一些字段之后,我需要添加一些字段以在详细视图中显示它们. /p>

,发生了一些有趣的事情 在原始示例中,主视图在详细信息视图中设置"detailItem"属性,然后详细信息视图显示该属性.

- (void)setDetailItem:(id) newDetailItem
{
if (_detailItem != newDetailItem) {
    _detailItem = newDetailItem;

    // Update the view.
    [self configureView];
}

我了解它的全部功能,所以在我玩的时候.我认为如果我使用self.detailItem而不是_detailItem也是一样的,因为它是该类的属性.

但是,当我使用

self.detailItem != newDetailItem

我实际上陷入了不断调用此方法的循环中,而我无法在模拟器中做任何其他事情.

我的问题是,下划线变量(ivar?)和属性之间的实际区别是什么? 我在这里阅读了一些帖子,这似乎只是一些客观的C约定,但实际上起到了一些作用.

解决方案

在实验过程中,您设置了一个无限循环,这就是模拟器无响应的原因.

setDetailItem:范围内调用self.detailItem会递归调用setDetailItem:,因为您的类为属性detailItem实现了自定义的setter方法.

我希望您参考 Apple文档关于已声明的属性,以获取有关属性,ivars等的信息;但简单来说,声明的属性是为类提供访问器方法的简化方法.现在不必通过编写自己的访问器方法(就像在Objective-C 2.0之前所做的那样),它们便可以通过属性语法为您生成.

I'm was playing around with the standard sample split view that gets created when you select a split view application in Xcode, and after adding a few fields i needed to add a few fields to display them in the detail view.

and something interesting happend in the original sample, the master view sets a "detailItem" property in the detail view and the detail view displays it.

- (void)setDetailItem:(id) newDetailItem
{
if (_detailItem != newDetailItem) {
    _detailItem = newDetailItem;

    // Update the view.
    [self configureView];
}

i understand what that does and all, so while i was playing around with it. i thought it would be the same if instead of _detailItem i used self.detailItem, since it's a property of the class.

however, when i used

self.detailItem != newDetailItem

i actually got stuck in a loop where this method is constantly called and i cant do anything else in the simulator.

my question is, whats the actual difference between the underscore variables(ivar?) and the properties? i read some posts here it seems to be just some objective C convention, but it actually made some difference.

解决方案

In the course of your experiment, you've set up an endless loop which is why the simulator goes non-responsive.

Calling self.detailItem within the scope of setDetailItem: calls setDetailItem: recursively since your class implements a custom setter method for the property detailItem.

I would refer you to the Apple documentation on declared properties for the scoop on properties, ivars, etc; but briefly, declared properties are a simplified way of providing accessor methods for your class. Rather than having to write your own accessor methods (as we had to do before Objective-C 2.0) they are now generated for you through the property syntax.

这篇关于目标C强调财产与自我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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