سؤال

I have 2 classes that I want to be able to access each others properties, but I don't want those properties accessed from anywhere else. Is there a way to do this? Is the only way to accomplish this through subclassing? Is there no way to establish a "special" relationship between two classes?

هل كانت مفيدة؟

المحلول

If I understand your question, you effectively want class A and class B, which are unrelated by inheritance, to be aware of more innards than are publicly advertised?

Say A has a property called innardsForB that only instances of B should access. You can use class extensions to declare the non-public interface to A.


A.h

@interface A:NSObject
... regular class goop here ...
@end


A-Private.h

@interface A()
@property(nonatomic, strong) Innards *innardsForB;
@end


A.m

#import "A.h"
#import "A-Private.h"

@implementation A
// because "A-Private.h" is #import'd, `innardsForB` will be automatically @synthesized
...
@end


B.m

#import "B.h"
#import "A-Private.h"

@implementation B
...
- (void)someMethod
{
     A *a = [self someASomewhere];
     a.innardsForB = [[Innards alloc] initForMeaning:@(42)];
}

نصائح أخرى

Protocols are designed for that purpose. You cannot stop 3rd party classes from implementing or using a protocol. Methods within these are public but not nessecarily part of the public interface.

I you want that classA access classB's properties and classC does't you simply déclare a reference of classA in ClassB and don't declare it in ClassB.

Example :

@interface ClassA
@property (nonatomic, strong) UILabel *label1;
@end

#import "ClassB.h"
#import "ClassA.h"  // To access public properties and all methods declared in ClassA.h

@implementation ClassB 

ClassA *classA = ....;
classA.label1.text = ...;

@end 

From this example, ClassB can access all public(déclared in CalssA.h) proerties and methods of ClassA.

You can use delegate also to do this.

On obj-c properties are protected. That means you can only accede properties by inheritance.

@interface A : NSObject{
    NSObject* prop;
}
@end

@implementation A
@end

@interface B : A
@end

@implementation B
- (void)protected{
    self->prop; // yep
}
@end

@interface XXX : NSObject
@end

@implementation XXX

- (void)test{
    A* a = [[A alloc] init];
    a->prop; // wrong, will not compile
}

@end

If you want to access hidden properties via method, you can use simply category hidden in implementation, or bridge. But there is no way to establish a "special" relationship between two classes. But you can enforce this relationship with your code design.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top