Objective-C - initialization of inherited variables of a subclass object

I have a class MyClass. I exaggerate here, but let MyClass have 1000 instance variables. Then I subclass MySubClass with all the variables of the MyClass instance, plus another one.

Question: if the MyObj object of the MyClass class is specified, is there an easy way to create the corresponding MyDerivedObj object of the MySubClass class, so that the instance variables MyDerivedObj are the same as the instance variables MyObj? By "the same" I mean the same thing in the sense that if the instance variable MyObj is a pointer to an object, the corresponding instance variable MyDerivedObj should point to the same memory.

+3
source share
4 answers

Actually, each instance of the object will have a different identifier; a different address and a different location on the heap.

Thus, instance variables A and instance variables B will always be in different places.

Now there is no reason why instance variables A and B cannot be enclosed in a structure that is allocated separately. Moreover, A and B can have an instance variable, which is a pointer to one copy of the structure full of values.

1000 , , . 0, . bcopy() , , . , .

+1

? , - ivar (NS (Mutable) Array/Dictionary/Set), /

myDerivedObj.collection = myObj.collection;

, MyObj "", , .

( - , / .)

+1

@public @protected, , .

0

" " MyClass MyDerivedClass.

[MyDerivedClass initByCopying:someMyObject plusSomeNewProperties:stuff] ->
  [MyClass initByCopying:someMyObject] ->
    [NSObject init] -> // alloc, etc.

:

@interface MyClass : NSObject { 
  int AA;
  // ...
  int ZZ;
}   
@end

@implementation MyClass

-initByCopying:(MyClass*)other;
{
  if (self = [super init])
  {
    self.AA=other.AA;
    //...
    self.ZZ=other.ZZ;
  }
  return self;
}

@end

@interface MyDerivedClass {
  int AAA;
}
@end

@implementation MyDerivedClass 

-initByCopying:(MyClass*)other withNewValue:(int)newVar;
{
  if (self = [super initByCopying:(MyClass*)other])
  {
    self.AAA = newVar;
  }
  return self;
}

@end

, 1000 -, kvc , , initByCopying.

, , , .

0
source

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


All Articles