NSMutableArray addObject: -[__NSArrayI addObject:]: unrecognized selector sent to instance

后端 未结 9 1046
太阳男子
太阳男子 2020-11-30 21:28

I have tried to initialize my NSMutableArray 100 ways from Sunday, and NOTHING is working for me. I tried setting it equal to a newly allocated and initialized NSMutableArra

9条回答
  •  伪装坚强ぢ
    2020-11-30 21:59

    The error came about as a result of attempting to add an object to an NSMutableArray type that was actually pointing to an NSArray object. This type of scenario is shown in some demo code below:

    NSString *test = @"test";
    NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
    [mutableArray addObject:test];
    NSArray *immutableArray = [[NSArray alloc] init];
    mutableArray = immutableArray;
    [mutableArray addObject:test]; // Exception: unrecognized selector
    

    From the above code, it is easy to see that a subclass type is being assigned to a superclass type. In Java, for instance, this would immediately have been flagged as an error (conversion error between types), and the problem resolved fairly quickly. To be fair to Objective-C, a warning is given when attempting to perform an incompatible assignment, however, this simply just does not seem to be enough sometimes and the result can be a real pain for developers. Fortunately, this time around, it was not myself who bore most of this pain :P

提交回复
热议问题