Why gcc warns of incompatible structure assignment with `self = [super initDesignatedInit]; 'call a derived class?

I have the following base / derived class setting in Objective-C:

@interface ASCIICodeBase : NSObject {
 @protected
  char code_[4];
}
- (Base *)initWithASCIICode:(const char *)code;
@end

@implementation ASCIICodeBase
- (ASCIICodeBase *)initWithCode:(const char *)code len:(size_t)len {
  if (len == 0 || len > 3) {
    return nil;
  }
  if (self = [super init]) {
    memset(code_, 0, 4);
    strncpy(code_, code, 3);
  }
  return self;
}
@end

@interface CountryCode : ASCIICodeBase
- (CountryCode *)initWithCode:(const char *)code;
@end
@implementation CountryCode
- (CountryCode *)initWithCode:(const char *)code {
  size_t len = strlen(code);
  if (len != 2) {
    return nil;
  }
  self = [super initWithCode:code len:len]; // here
  return self;
}
@end

On the line labeled “here,” the following gcc warning appears:

warning: incompatible Objective-C types assigning 'struct ASCIICodeBase *', expected 'struct CurrencyCode *'

Is there something wrong with this code, or should I return ASCIICodeBasereturn id? Or maybe use a listing on the here line?

+3
source share
2 answers

Use (id)as return type.

Objective-C does not support covariant declarations. Consider:

@interface NSArray:NSObject
+ (id) array;
@end

+array NSArray, NSMutableArray. , - . - Objective-C , (NSArray*), `(NSMutableArray *). , . , , , .

... , , . , , , , , (id).

. -init* , (). , , (id) .

- .


, LLVM instancetype, id , . , " , isKindOfClass: , ".

+4

(CountryCode *). ASCIICodeBase *, , CountryCode *

:

self = (CountryCode *) [super initWithCode:code len:len];

(id). Objective-C.

+4

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


All Articles