2011-02-23 78 views
3

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

相关代码

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 alloc] init]; testPage.questions的类型从NSMutableArray *更改为__NSArrayL *(或__NSArrayI *,不确定)。我怀疑这是问题,但我觉得这很奇怪。任何人都知道这里发生了什么?

回答

4

问题是您已声明财产为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]; 
+0

嗯,没想到会这样,但它的工作原理!我使用了'copy',因为在这里有很多问题建议在任何可变的东西时使用复制。谢谢:D – SpacyRicochet 2011-02-23 22:57:13

+0

@SpacyRicochet:当你想确保得到的属性值是*不可变*时,你可以使用'copy'。你最常使用'NSString'属性来看这个:你'复制'它们以使得字符串本身不能从你下面改变。由于你的财产*被认为是可变的,所以你不能使用'copy'。 :) – 2011-02-23 23:53:28

+0

谢谢!这将花费我更多的时间来弄清楚。 :) – 2011-04-12 15:21:36

2

@property(nonatomic,copy)这个setter声明“复制”可能强制转换为NSArray为什么不保留或分配?我仍然会保留

+0

+1,虽然新值不会转换为“NSArray”。该方法实际上是制作一个不可变的副本。 – 2011-02-23 22:43:26

+0

谢谢,BTW有什么办法来看看这些指令,如@property生成什么代码? – Michal 2011-02-23 22:50:38

+0

除了看原始装配,还没有。 – 2011-02-23 22:52:33

1

您还可以创建一个可变复制方法如下:

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

以后也发现了这个。好的方法,虽然我用它来返回我想改变的正常数组的方法。 – SpacyRicochet 2011-03-29 22:48:31