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

后端 未结 9 1016
太阳男子
太阳男子 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

    0 讨论(0)
  • 2020-11-30 22:00

    Have some indexes (into a data array elsewhere) and wanted to have them in numerical order (for a good reason). Crashing until added mutableCopy at the end. Totally puzzled, until I recalled that using Objective-C literal @[] returns a non-mutable array.

    NSMutableArray *a = [@[@(self.indexA), @(self.indexB)] mutableCopy];
    NSLog(@"%@", a);
    [indexArray sortUsingComparator: ^(NSNumber *obj1, NSNumber *obj2) {
        return [obj1 compare:obj2];
    }];
    NSLog(@"%@", a);
    

    Thanx, Zak!

    0 讨论(0)
  • 2020-11-30 22:01

    I got bitten by this exception for a typo I've made, maybe it'll save someone 5 min. of their time:

    I wrote:

    NSMutableArray *names = [NSArray array];
    

    instead of:

    NSMutableArray *names = [NSMutableArray array];
    

    The compiler has no problem with that because NSMutableArray is also an NSArray, but it crashes when trying to add an object.

    0 讨论(0)
提交回复
热议问题