Why does a (copy, nonatomic) NSMutableArray property create NSArrays?

后端 未结 2 1203
情书的邮戳
情书的邮戳 2021-01-31 04:52

I made a mistake while creating a TableView class, and accidentally kept my @property as copy when I defined it:

@property         


        
2条回答
  •  渐次进展
    2021-01-31 05:07

    -copy, as implemented by mutable Cocoa classes, always returns their immutable counterparts. Thus, when an NSMutableArray is sent -copy, it returns an NSArray containing the same objects.

    Because words has the memory qualifier copy, this line:

    NSMutableArray *mutWords = [[NSMutableArray alloc] initWithArray:fixedWords];
    self.words = mutWords;
    

    Expands out to:

    NSMutableArray *mutWords = [[NSMutableArray alloc] initWithArray:fixedWords];
    self.words = [mutWords copy];
    

    Given that NSMutableArray is a subclass of NSArray, the compiler doesn't complain, and you now have a ticking time bomb on your hands because NSArray does not recognize it's mutable subclass' methods (because it cannot mutate it's contents).

提交回复
热议问题