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

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

    I would like to tip my hat to Georg Fritzsche. I did end up needing to use (copy) instead of (retain), and I would not have known what to do without his input.

    //@property (copy) NSMutableArray *array;
    @property (nonatomic, copy) NSMutableArray *array; //overridden method is non-atomic as it is coded and should be reflected here.
    

    If you wish to use (copy) on a mutable object you must override the "setter" method as follows...

    - (void)setArray:(NSArray *)newArray {
    
        if ( array != newArray ) { 
            [array release];
            array = [newArray mutableCopy];
    //      [array retain]; // unnecessary as noted by Georg Fritzsche
        }
    
        return;
    }
    

    NOTE: You will get a compiler warning: Incompatible Objective-C types initializing 'struct NSArray *', expected 'struct NSMutableArray *' I chose to declare the newArray parameter as an (NSArray *), because you are given the flexibility to have any array passed and correctly copied to your (NSMutableArray *) variable. If you wish to declare the newArray parameter as an (NSMutableArray *) you will still need to leave the mutableCopy method in place to get your desired results.

    Cheers to Georg! Z@K!

提交回复
热议问题