NSMutableArray 总是空的? [英] NSMutableArray always empty?
问题描述
理解Obj-C的记忆和一些概念还是有些困难.
Still have some difficulties to understand Obj-C's gestion of memory and some of its concepts.
所以我的主类包含一个 NSMutableArray
包含一些字符和他们的武器列表.是这样的:
So my main class contains a NSMutableArray
containing some characters and their list of weapons. It's like this :
在主类.h
@property (nonatomic, retain) NSMutableArray *players;
在 Main class.m 的 init
for(int i = 0 ; i < 30 ; i++)
{
[players addObject:[[PlayerInGame alloc] init:[self.tabPlayers objectAtIndex:i] :[self.tabWeapons:objectAtIndex:i]]];
}
PlayerInGame.h
@property (nonatomic, retain) NSMutableArray *weaponsList;
PlayerInGame.m
- (id) init : (Player*) player : (Weapon*) weapon
{
[self.weaponsList addObject:weapon];
// Then I try NSLog of weaponsList's count.
}
这里的武器列表总是空的.怎么了?
Here weaponsList is always empty. What is wrong?
推荐答案
其他答案是对的.在任何其他语言上,如果您引用未分配的对象,您将获得 NullPointerException.但是在目标 C 中,发送到 nil 的方法只返回 0,它不会使应用程序崩溃.如果您想进一步阅读,请阅读 this
The other answers are right. On any other language if you reference a unallocated object you will get a NullPointerException. But in objective C the method sent to nil just returns 0 and it won't crash the app.. If you want further read, read this
这就是为什么
[self.weaponsList addObject:weapon];
没有崩溃,而在 java 中,如果您尝试将对象添加到未分配的数组中,您的程序将崩溃.. 正如其他答案所指出的,声明
didn't crash, while in java if you try to add object to a unallocated array your program will crash.. As other answers pointed out, the statement
self.weaponsList = [[[NSMutableArray alloc] init] autorelease];
分配内存来存储数组,并且引用返回给变量weatherList.现在武器列表 != nil.
alloc memory to store array, and a reference is given back to to variable weaponList. Now weaponList != nil.
这篇关于NSMutableArray 总是空的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!