如何建立私有财产? [英] How to make a private property?

查看:74
本文介绍了如何建立私有财产?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的*.m文件中建立一个私有财产:

I tried to make a private property in my *.m file:

@interface MyClass (Private)
@property (nonatomic, retain) NSMutableArray *stuff;
@end

@implementation MyClass
@synthesize stuff; // not ok

编译器声称没有声明stuff属性.但是有东西.只是在一个匿名类别中.让我猜:不可能.其他解决方案?

Compiler claims that there's no stuff property declared. But there's a stuff. Just in an anonymous category. Let me guess: Impossible. Other solutions?

推荐答案

您要使用类扩展名"而不是类别:

You want to use a "class extension" rather than a category:

@interface MyClass ()
@property (nonatomic, retain) NSMutableArray *stuff;
@end

@implementation MyClass
@synthesize stuff; // ok

类扩展是在Objective-C 2.0中创建的,部分目的就是为此目的而创建的.类扩展的优点是,编译器将它们视为原始类定义的一部分,因此可以警告实现不完整.

Class extensions were created in Objective-C 2.0 in part specifically for this purpose. The advantage of class extensions is that the compiler treats them as part of the original class definition and can thus warn about incomplete implementations.

除了纯私有属性外,您还可以创建内部可读写的只读公共属性.可以仅在类扩展中重新声明属性以更改访问权限(只读vs.读写),但在声明中必须完全相同.因此,您可以执行以下操作:

Besides purely private properties, you can also create read-only public properties that are read-write internally. A property may be re-declared in a class extensions solely to change the access (readonly vs. readwrite) but must be identical in declaration otherwise. Thus you can do:

//MyClass.h
@interface MyClass : NSObject
{ }
@property (nonatomic,retain,redonly) NSArray *myProperty;
@end

//MyClass.m
@interface MyClass ()
@property (nonatomic, retain, readwrite) NSArray *myProperty;
@end

@implementation MyClass
@synthesize myProperty;
//...
@end

这篇关于如何建立私有财产?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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