Friend classes in Objective-C

前端 未结 2 1249
眼角桃花
眼角桃花 2020-12-08 21:45

Is there any way to create something like friend classes in Objective-C?

相关标签:
2条回答
  • 2020-12-08 21:51

    There is no such thing as a friend class in ObjC.

    And to access a private variable of another class you don't even need to be declared as a friend. For example, you can use the runtime functions

    id the_private_ivar;
    object_getInstanceVariable(the_object, "_ivar_name", &the_private_ivar);
    

    to get the_object->_ivar_name, bypassing compiler checks.

    0 讨论(0)
  • 2020-12-08 22:05

    First declare a "private property" using the standard class extension method:

    // 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
    

    Then recreate the properties in a category:

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

    This interface is only accessible to those who import VisualNotePlayer+Views.h

    0 讨论(0)
提交回复
热议问题