只是为了平息我的好奇心,
比方说,我正在使用 XCode 在 iOS 的 Objective-C 中创建一个项目/框架,我想添加一个方法,该方法将对特定项目进一步可见并对其他项目隐藏。
如果这不能让你了解我的想法, 假设我正在创建一个 XCode 项目,该项目进一步分为三个不同的项目(比如 A、B、C)。当我开始实际实现时,我希望项目 A 中的所有类方法对项目 B 可见,但希望对项目 C 隐藏它们。
有没有办法在 iOS Objective-C/Swift 中实现类似的东西?
最佳答案
正如 Mindaugas 在其中一条评论中提到的,您可以为此目的使用类扩展。
类扩展通常用于使用额外的私有(private)方法或属性扩展公共(public)接口(interface),以便在类本身的实现中使用。
例如 .h 包含
@interface Person : NSObject
@property(nonatomic, copy) NSString *firstName;
@property(nonatomic, copy) NSString *lastName;
- (void)setDateOfBirth:(NSDate *)date;
@end
.m会有
@interface Person()
@property(nonatomic, strong) NSDate *dateOfBirth;
- (void)calculateMyAge;
@end
@implementation Person
- (void)setDateOfBirth:(NSDate *)date
{
self.dateOfBirth = date;
//Some more code goes here
}
- (void)calculateMyAge
{
//Do something with self.dateOfBirth here
}
@end
在这里,我们将 @property
dateOfBirth 和方法 calculateMyAge 设为接口(interface) Person 私有(private),并在 @implementation
block 下实现。
@interface Person()
只不过是类扩展(或无名类别或匿名类别)。
现在回到最初的问题,您想将其公开给您的框架,而对外公开。
假设您希望 Person 类有一个返回全名(附加名字和姓氏)的方法。但是,您希望框架的内部用途。
您可以为此创建一个单独的头文件。
Person+InternalHeader.h
将有方法的声明
@interface Person()
- (NSString *)fullName;
@end
可以导入
#import "Person+InternalHeader.h"
进入您的 Person.m
文件并在 @implementation
block 下您可以为该方法实现主体。
@implementation Person
//other code
- (NSString *)fullName
{
return [self.firstName stringByAppendingFormat:@" %@",self.lastName];
}
@end
您始终可以将 Person+InternalHeader.h 导入到您的其他类中并使用 fullName 方法。
为什么是扩展而不是类别?
扩展使您能够覆盖属性或向现有父类添加新属性。您也可以始终覆盖子类中扩展中定义的方法的默认行为。对于类别,它只是将方法添加到现有对象。
例如,假设有一个继承自类 Person 的类 Doctor。
@interface Doctor : Person
现在您希望 fullName
方法返回“Dr.”。前置。您可以简单地覆盖 Doctor.m
文件中的 fullName
行为。
@implementation Doctor
- (NSString *)fullName
{
NSString *fullName = [super fullName];
return [@"Dr. " stringByAppendingString:fullName];
}
@end
关于ios - 编写一个对一个项目可见而对其他项目隐藏的类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41894916/