我有一个nsmutablearray,它被定义为一个属性,被合成,并且我分配了一个新创建的nsmutablearray实例。但在这之后,每当我尝试向nsmutablearray添加对象时,我的应用程序总是崩溃。
第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

第m页
@implementation Page
@synthesize name, image, questions;
@end

相关代码
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()]];

调试器显示,当我使用testpage.questions的类型从nsmutablearray*更改为nsarrayl*(或nsarrayi*,不确定)时。我怀疑这是问题所在,但我觉得非常奇怪。有人知道这里发生了什么吗?

最佳答案

问题是你已经宣布该财产为“cc>”。这意味着您的setter将被实现如下:

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

更关键的是,如果您copy一个数组(无论是不可变的还是可变的),您总是会得到一个不可变的-copy
因此,要修复这一点,将属性更改为NSArray而不是retain,并修复此内存泄漏:
testPage.questions = [[NSMutableArray alloc] init];

应该是:
testPage.questions = [NSMutableArray array];

09-04 14:02
查看更多