NSMutableArray 新协议类型

NSMutableArray new with Protocol type

  1. 如何消除警告而不使用 [@[] mutableCopy]:

//Incompatible pointer types assigning to 'NSMutableArray *' from 'NSMutableArray *'

@protocol Coordinatorable <NSObject>

@property (nonatomic, strong, readonly) UINavigationController *presenter;
@property (nonatomic, strong, readonly) NSMutableArray<Coordinatorable>*childCoordinators;

@end


self.childCoordinators = [[NSMutableArray alloc] init]; //Incompatible pointer types assigning to 'NSMutableArray<Coordinatorable> *' from 'NSMutableArray *'
self.childCoordinators = [@[] mutableCopy]; //works without issue

How do I get rid of the warning and not use [@[] mutableCopy]:

投出结果:

self.childCoordinators = (NSMutableArray<Coordinatorable>*)[[NSMutableArray alloc] init];

我认为你的问题的原因在于你如何声明你的 属性。该行:

@property (nonatomic, strong, readonly) NSMutableArray<Coordinatorable>*childCoordinators;

应该是:

@property (nonatomic, strong, readonly) NSMutableArray<id<Coordinatorable>>*childCoordinators;

引用符合协议的对象时需要使用id<SomeeProtocol>