使用 initWithObjects: 会导致崩溃,但 initWithCapacity: 后跟 addObject: 不会崩溃
一个非常奇怪的问题。我必须在 - (void)viewDidLoad
中初始化一个数组。
数组 prjMemberArray
被声明为属性:
@property(nonatomic, retain) NSMutableArray* prjMemberArray;
如果我将其
prjMemberArray = [[NSMutableArray alloc] initWithObjects:@"someone",@"someone",@"someone" ,nil];
与在 viewDidUnload
中调用的 release
一起使用,
那么当视图加载时,它将崩溃立即但是当我使用这个时:
prjMemberArray = [[NSMutableArray alloc] initWithCapacity:0];
[prjMemberArray addObject:@"someone"];
效果很好。谁能解释一下吗?我使用故事板来呈现当前视图控制器,如下所示:
UIStoryboard* sb = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
prj_Detail = [sb instantiateViewControllerWithIdentifier:@"ProjectDetailVC"];
[self presentModalViewController:prj_Detail animated:YES];
其中 prjMemberArray 是 prj_Detail 的属性。
A really strange problem. I have to init an array in - (void)viewDidLoad
.
The array, prjMemberArray
is declared as a property:
@property(nonatomic, retain) NSMutableArray* prjMemberArray;
If I use this
prjMemberArray = [[NSMutableArray alloc] initWithObjects:@"someone",@"someone",@"someone" ,nil];
with release
called in viewDidUnload
,
then when the view loaded , it will crashes immediately But when I use this:
prjMemberArray = [[NSMutableArray alloc] initWithCapacity:0];
[prjMemberArray addObject:@"someone"];
it works well. Can anyone explain this? I use a storyboard to present the current view controller, like this:
UIStoryboard* sb = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
prj_Detail = [sb instantiateViewControllerWithIdentifier:@"ProjectDetailVC"];
[self presentModalViewController:prj_Detail animated:YES];
Where prjMemberArray
is a property of prj_Detail
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您确定您没有拼写错误的项目并在崩溃场景中编写了例如
"someone"
而不是@"someone"
吗?Are you sure you have not misspelled items and written e.g.
"someone"
instead of@"someone"
in the crashing scenario?引用属性时不要忘记使用 self。这是一种安全的声明方式,无需担心泄漏:
标头:
实现:
@property 为变量创建 getter 和 setter,但经常与变量本身混淆。当他们发布 XCode4 时,我相信他们添加了通过执行以下操作来设置您希望实例变量命名的功能:
在 XCode4 之前,您只需执行以下操作:
那么 @property 在幕后所做的事情有点像这样:
所以不要将 @property 视为变量本身,并记住在引用它们时始终使用 self 。这应该可以避免你很多痛苦,也可以避免一些内存泄漏。
Don't forget to use self when referring to properties. Here's the a safe way to declare that without having to worry about leaks:
Header:
Implementation:
@property creates the getter and setter for your variable but is often confused for a variable itself. When they released XCode4 I believe they added the ability to set what you want the instance variable to be named by doing:
Before XCode4 you simply did:
So what @property is doing behind the scenes is a little something like this:
So don't think of @property as a variable itself and remember to always use self when referring to them. That should save you a lot of pain and a few memory leaks as well.