iPhone - Crash using addObject on a NSMutableArray

前端 未结 5 1530
悲哀的现实
悲哀的现实 2020-12-10 19:42

I have a problem here. Or Maybe I\'m really tired...

I have a class :

@interface THECLASS : UIViewController  {
    NSMuta         


        
5条回答
  •  Happy的楠姐
    2020-12-10 20:11

    Answer is buried in the comments to the "accepted" answer. I came here from Google and it fixed my problem, so ... to make it clearer, based on @e.James's comment:

    When you implement the "NSCopying" protocol, and implement "copyWithZone", you MUST NOT use "copy" on your internal mutable arrays - this DOES NOT copy the array (instead, it creates a non-mutable copy).

    e.g. from my own code:

    // Class: MyClass
    
    @property(nonatomic, retain) NSMutableArray* mutArray;
    
    -(id)copyWithZone:(NSZone *)zone
    {
        MyClass* other = [[MyClass alloc] init];
    
    //  other.mutArray = [self.mutArray copy]; // WRONG!
        other.mutArray = [self.mutArray mutableCopy]; // CORRECT!
    
        return other;
    }
    

提交回复
热议问题