Objective-C中的朋友类

Cas*_*ash 18 objective-c

有没有办法在Objective-C中创建像朋友类这样的东西?

Cas*_*ash 30

首先使用标准类扩展方法声明"私有属性":

// VisualNotePlayer.h
@interface VisualNotePlayer : NSObject<NotePlayer>{
    @private
    UIView *_currentView;
}

// VisualNotePlayer.m
@interface VisualNotePlayer()
@property (nonatomic, retain) UIView *currentView;
@end

@implementation VisualNotePlayer
@synthesize currentView=_currentView;
...
@end
Run Code Online (Sandbox Code Playgroud)

然后重新创建类别中的属性:

// VisualNotePlayer+Views.h
@interface VisualNotePlayer(Views)
@property (nonatomic, retain) UIView *currentView;
@end
Run Code Online (Sandbox Code Playgroud)

只有导入的人才能访问此界面 VisualNotePlayer+Views.h


ken*_*ytm 5

在ObjC中没有朋友类这样的东西.

要访问另一个类的私有变量,您甚至不需要声明为朋友.例如,您可以使用运行时功能

id the_private_ivar;
object_getInstanceVariable(the_object, "_ivar_name", &the_private_ivar);
Run Code Online (Sandbox Code Playgroud)

得到the_object->_ivar_name,绕过编译器检查.