I am porting cpp code into Objective C.
In cpp
we can add a class as friend class
to another class and use 开发者_JAVA百科all its public functions and variables.
I know that Objective C does not support friend class
concept.
How do i make a class as a friend to another class in Objective C
If you have two tightly-coupled classes, then you can use some simple tricks to expose a simpler public interface. For example,
In Banana.h
:
@interface Banana : NSObject
- (BOOL)isPeeled;
@end
In Monkey.h
:
@interface Monkey : NSObject
- (void)eat:(Banana *)aBanana;
@end
In BananaPrivate.h
:
@interface Banana (PrivateMethods)
- (void)peel;
@end
Then your Monkey.m
file can import BananaPrivate.h
to get the private functions. If you're writing a framework, then you don't include BananaPrivate.h
in your framework headers.
This is the same way encapsulation is done in C. In my opinion it's significantly less broken than the friend
keyword in C++
, but it's beyond the scope of this answer to explain why.
You can also expose private member variables this way if you implement Banana as a class cluster, but that's kind of insane and I don't recommend it. If you need even closer coupling between classes you might want to use C idioms for that part of the code.
精彩评论