在界面块中同时使用属性和ivars的Objective-c现代运行时 [英] Objective-c modern runtime using both properties and ivars in interface block

查看:88
本文介绍了在界面块中同时使用属性和ivars的Objective-c现代运行时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了代码示例(来自《 Beginning iPhone 4 Development》一书),它们都在接口块内部声明了ivars,然后为它们声明了属性.像这样:

I've seen code examples (from the book Beginning iPhone 4 Development) where they both declare ivars inside the interface block and then declare properties for the same. Like this:

@interface ViewController : UIViewController {
    UITableView *table;
}

@property (nonatomic, retain) IBOutlet UITableView *table;

这样做的目的/好处是什么?据我了解,对于现代运行时版本(iPhone和64位OS X应用程序),您只需要声明属性,而无需在接口块内声明ivars.根据

What would be the purpose/benefit of this? As I understand that with the modern runtime version (iPhone and 64-bit OS X applications) you only need to declare properties and can leave out declaring the ivars inside the interface block. According to this answer in a similair thread it would be for debugging purposes. But are there any other benefits except for debugging that you would use this approach?

干杯

彼得

推荐答案

明确声明ivars使您可以在内部为ivar使用专用类型.

Explicitly declaring ivars gives you the possibility to internally use a specialized type for the ivar.

一个典型的例子是一个内部可变对象,可以从外部以只读,不变的方式对其进行访问.

A typical example is an internally mutable object that can be accessed from outside in a readonly, immutable way.

示例:

@interface Foo : NSObject
@property (readonly) NSArray *bars;
@end

@implementation
{
    NSMutableArray *bars;
}

@synthesize bars;

- (void)addBar:(Bar *)bar
{
    [bars addObject:bar];
}
@end

当然,从bars属性返回的对象并不是真正不变的.但关键是该API并未揭示其可变性.

Of course the object returned from the bars property is not really immutable. But the point is that the API does not reveal its mutability.

请注意,我使用了新颖的实现中的private-ivars-in实施样式.这取决于现代运行时以及clang编译器.

Note that I used the fancy new private-ivars-in-implementation style. It's depending on the modern runtime as well as the clang compiler.

这篇关于在界面块中同时使用属性和ivars的Objective-c现代运行时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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