简体   繁体   English

Objective-C包级属性

[英]Objective-C Package level Property

I am creating an iPhone custom framework which should be able to be integrated into any iPhone app. 我正在创建一个iPhone自定义框架,它应该能够集成到任何iPhone应用程序中。

I have created some properties in one of the public header files of my framework. 我在我的框架的一个公共头文件中创建了一些属性。 I want to give @package level access to those properties, so that those properties can be accessed only with in the classes inside the framework. 我想给@package级别访问这些属性,以便只能在框架内的类中访问这些属性。

I do not want the user to use those properties. 我不希望用户使用这些属性。

Please tell me whether doing this is possible. 请告诉我这是否可行。 If yes, please give me some idea on how to achieve this!. 如果有,请告诉我如何实现这一目标!

First you should know that there is no way to completely forbid a user of your library to call a method. 首先,您应该知道没有办法完全禁止您的库用户调用方法。 Even if you don't declare it in your header, a user could declare it on its own and use it. 即使您没有在标题中声明它,用户也可以单独声明它并使用它。 He would still have to find out the name of your property though, for instance by running classdump on your library. 他仍然需要找出你的财产的名称,例如在你的图书馆上运行classdump。

Therefore in Objective-C, we make properties private by not declaring them in the header (which is the public part of your class), but by declaring them in the implementation (which is the "private" part of your class). 因此,在Objective-C中,我们通过不在标题(这是您的类的公共部分)中声明属性来使属性变为私有,而是通过在实现中声明它们(这是类的“私有”部分)。

If you create another header which contains a category on your class, you can add some properties to it that will not be in the main header - so not on the public declaration of your class - but that can still be imported by other classes of your library that know about this header. 如果你创建了另一个包含类的类别的标题,你可以添加一些不在主标题中的属性 - 所以不要在你的类的公开声明中 - 但仍然可以由你的其他类导入知道这个标题的库。

For instance: 例如:

MyClass+SecretProperties.h:

@interface MyClass ()
@property (strong) NSString *secretString;
@end

MyClass.m:

#import "MyClass.h"
#import "MyClass+SecretProperties.h"
@implementation MyClass
@synthesize secretString; // Depending on your runtime, you may not even need to this - properties are auto-synthesized in the latest SDKs.
…
@end

OtherClass.m:

#import "MyClass.h"
#import "MyClass+SecretProperties.h"

// Now you can use secretString on instances of MyClass

Then since you only export MyClass.h with your library, users have no idea that there is a secretString property :) This is the closest you can get to a @package scope AFAIK. 然后由于你只用你的库导出MyClass.h,用户不知道有一个secretString属性:)这是你可以到达@package范围AFAIK最近的。

If you want to make those property as private then use below things. 如果您想将这些属性设为私有,请使用以下内容。 In your .m file use extension characteristics of objective c. 在.m文件中使用目标c的扩展特性。

@interface InitialViewController ()
//declare your property here
@end 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM