NSMutableArray crashes when added after proper initialization

I have an NSMutableArray defined as a property synthesized, and I assigned a newly created instance of NSMutableArray. But after that, my application always crashes when I try to add an object to NSMutableArray.

Page.h

@interface Page : NSObject  
{  
    NSString *name;  
    UIImage *image;  
    NSMutableArray *questions;  
}
@property (nonatomic, copy) NSString *name;  
@property (nonatomic, retain) UIImage *image;  
@property (nonatomic, copy) NSMutableArray *questions;  
@end

Page.m

@implementation Page  
@synthesize name, image, questions;  
@end  

Corresponding code

Page *testPage = [[Page alloc] init];  
testPage.image = [UIImage imageNamed:@"Cooperatief  leren Veenman-11.jpg"];  
testPage.name = [NSString stringWithString:@"Cooperatief  leren Veenman-11.jpg"];  
testPage.questions = [[NSMutableArray alloc] init];  
[testPage.questions addObject:[NSNumber numberWithFloat:arc4random()]];  

The debugger shows that at the moment when I use testPage.questions = [[NSMutableArray alloc] init];, the type testPage.questions changes from NSMutableArray * to __NSArrayL * (or __NSArrayI *, not sure). I suspect this is a problem, but I find it extremely strange. Does anyone know what is going on here?

+3
source share
3 answers

, copy. , :

- (void) setQuestions:(NSMutableArray *)array {
  if (array != questions) {
    [questions release];
    questions = [array copy];
  }
}

, -copy ( ), NSArray.

, , retain copy, :

testPage.questions = [[NSMutableArray alloc] init];

:

testPage.questions = [NSMutableArray array];
+4

@property (, ) setter "copy", , NSArray, ?

+2

You can also create a mutable copy method as follows:

- (void)setQuestions:(NSMutableArray *)newArray
{
    if (questions != newArray) 
    {
        [questions release];
        questions = [newArray mutableCopy];
    }
}
+1
source

Source: https://habr.com/ru/post/1794267/


All Articles