[英]NSMutableArray crashes when adding after proper initialization
I have an NSMutableArray defined as a property, synthesized and I have assigned a newly created instance of an NSMutableArray. 我有一个NSMutableArray定义为属性,合成,我已经分配了一个新创建的NSMutableArray实例。 But after this my application always crashes whenever I try adding an object to the NSMutableArray.
但在此之后,每当我尝试将对象添加到NSMutableArray时,我的应用程序总是会崩溃。
Page.h
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
Page.m
@implementation Page
@synthesize name, image, questions;
@end
Relevant 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 reveals that the moment I use testPage.questions = [[NSMutableArray alloc] init];
调试器显示我使用
testPage.questions = [[NSMutableArray alloc] init];
的那一刻testPage.questions = [[NSMutableArray alloc] init];
the type of testPage.questions changes from NSMutableArray* to __NSArrayL* (or __NSArrayI*, not sure). testPage.questions的类型从NSMutableArray *更改为__NSArrayL *(或__NSArrayI *,不确定)。 I suspect this to be the problem, but I find it extremely odd.
我怀疑这是问题,但我觉得这很奇怪。 Anyone know what's happening here?
有谁知道这里发生了什么?
The problem is that you've declared the property as copy
. 问题是您已将该属性声明为
copy
。 This means your setter is going to be implemented something like this: 这意味着您的setter将实现如下:
- (void) setQuestions:(NSMutableArray *)array {
if (array != questions) {
[questions release];
questions = [array copy];
}
}
The kicker here is that if you -copy
an array (whether immutable or mutable), you will always get an immutable NSArray
. 这里的踢球者是,如果你
-copy
一个数组(无论是不可变的还是可变的),你将永远得到一个不可变的NSArray
。
So to fix this, change the property to be retain
instead of copy
, and also fix this memory leak: 因此,要解决此问题,请将属性更改为
retain
而不是copy
,并修复此内存泄漏:
testPage.questions = [[NSMutableArray alloc] init];
It should be: 它应该是:
testPage.questions = [NSMutableArray array];
@property (nonatomic, copy) This setter declaration "copy" probably cast to NSArray why not retain or assign? @property(nonatomic,copy)这个setter声明“copy”可能会转换为NSArray为什么不保留或赋值? I would retain anyway
无论如何我会保留
You can also create a mutable copy method like so: 您还可以创建一个可变复制方法,如下所示:
- (void)setQuestions:(NSMutableArray *)newArray
{
if (questions != newArray)
{
[questions release];
questions = [newArray mutableCopy];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.