Interconnected classes and subclasses in Objective-C

I have 2 sets of immutable / mutable types.

@class AAA; @class BBB; @class MutableAAA; @class MutableBBB; @interface AAA : NSObject @property (readonly,nonatomic,copy) BBB* bbb; @end @interface BBB : NSObject @property (readonly,nonatomic,copy) AAA* aaa; @end @interface MutableAAA : AAA @property (readwrite,nonatomic,copy) MutableBBB* bbb; @end @interface MutableBBB : BBB @property (readwrite,nonatomic,copy) MutableAAA* aaa; @end 

Since Objective-C supports covariance of the return type, this is completely legal, but the problem is that the two classes reference each other, I don’t know how to tell the MutableBBB compiler MutableBBB subclass BBB before defining it.

Of course, I can fall back to the category to get around this, but I want to define them in the main module of the interface, because this is part of the important definition of the class, and not an additional method.

Clang is currently generating a warning. How can I do this without warning?

Update

My intention is a mutable class type to enable in-place editing on an object tree. readonly/readwrite doesn't matter. I think I have two options that I want to avoid.

  • Use categories.
  • Adding a separate modified version access option. (e.g. the -mutableBytes method in NSMutableData )

I just want to know if there is some unknown function that I don't know yet that activates this cross-reference subclass.

+4
source share
1 answer

This is a question that is easier than it seems thanks to recent advances in this language. It is for this reason that class extensions exist and to illustrate my point, I defined the interface and the pseudo-method file.

 // CFIAAAsAndBBBs.h @class AAA; @class BBB; @interface AAA : NSObject @property (readonly,nonatomic,copy) BBB* bbb; @end @interface BBB : NSObject @property (readonly,nonatomic,copy) AAA* aaa; @end @interface MutableAAA : AAA @end @interface MutableBBB : BBB @end 

First, pay attention to the changes made to the title. Instead of having readwrite properties set in the header, you move them to the implementation file. If you need to expose them to any other object, simply declare a different set of readwrite properties using the superclasses you defined instead of their mutable copies. This way you avoid exposing mutability, and you can safely override a property in a class extension later if you need to readwrite it internally. Speaking of the internal properties of readwrite , here's the m file:

 // CFIAAAsAndBBBs.m #import "CFIAAAsAndBBBs.h" @interface MutableAAA () @property (readwrite,nonatomic,copy) MutableBBB* bbb; @end @interface MutableBBB () @property (readwrite,nonatomic,copy) MutableAAA* aaa; @end //... 

No more warnings, everyone leaves the winner.

+4
source

Source: https://habr.com/ru/post/1488617/


All Articles