是的我知道我应该阅读更多有关内存管理的内容,确实试图找到并理解,但是当我发布NSMutableArray时,我仍然不知道为什么这段代码会崩溃(参见代码)。我最初做alloc / init。
- (void)readSelectedPlayers {
//Prepare File Manager
NSString *filePath = [self dataFilePath];
NSFileManager *fileMgr;
fileMgr = [NSFileManager defaultManager];
//
NSMutableArray *theObjects = [[NSMutableArray alloc] initWithCapacity:0];
NSMutableArray *activePlayersArray = [[NSMutableArray alloc] initWithCapacity:0];
NSMutableArray *readyPlayers = [[NSMutableArray alloc] initWithCapacity:0];
//
// Select all keys from the plist
NSMutableDictionary *playerDict = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
NSArray *allMyKeys = [playerDict allKeys];
//
for(NSString * myKey in allMyKeys) {
theObjects = [playerDict valueForKey:myKey];
if ([[theObjects objectAtIndex:1] intValue] == YES) {
[activePlayersArray addObject:myKey];
}
}
NSLog(@"activePlayersArray: %@", activePlayersArray);
//
//========CALL AccesQuestionDB MODULE TO SHUFFLE PLAYERS=========//
AccessQuestionsDB *shufflePlayersFunction = [AccessQuestionsDB new];
readyPlayers = [shufflePlayersFunction shufflePlayers: activePlayersArray];
NSLog(@"readyPlayers: %@", readyPlayers);
//
[readyPlayers release];
[theObjects release];
[activePlayersArray release];
}
这些行之间的'//'只是为了让代码更好地格式化。
答案 0 :(得分:1)
您不需要分配/ init readyPlayers
变量,因为您将从shufflePlayers
方法获取它。从readyPlayers
返回的shufflePlayers
也应该已经自动释放,因此您无需释放它。
答案 1 :(得分:0)
为什么要分配实例NSMutableArray
然后将其设置为NSArray
?当你这样做
NSMutableArray *theObjects = [[NSMutableArray alloc] initWithCapacity:0];
创建容量为0的NSMutableArray
并将其存储到名为theObjects
的指针中。稍后你会这样做:
theObjects = [playerDict valueForKey:myKey];
将您之前创建的指针设置为[playerDict valueForKey:myKey]
。这样,您将丢失指向已分配NSMutableArray
的原始指针。当您将release
发送至theObjects
时,您无权访问最初创建的NSMutableArray
!
我不确定你在这里要做什么,但我会这样做:
NSArray *theObjects;
// some code
for(NSString * myKey in allMyKeys) {
theObjects = [playerDict valueForKey:myKey];
// some more code
}
// don't release "theObjects". It's just a pointer...
正如tia指出的那样,readyPlayers
数组也是如此。
答案 2 :(得分:0)
您为readyPlayers变量分配内存,但随后将其指向其他内存段:
readyPlayers = [shufflePlayersFunction shufflePlayers: activePlayersArray];
readPlayer现在已经自动释放了。你丢失了先前分配的内存的句柄。
您需要做的主要是:
if (readplayer!= nil){
[readplayer release];
}
readplayer = [[shufflePlayersFunction shufflePlayers: activePlayersArray] retain];
以后......当你完成时,请确保再次释放。
但是......不要试试这个!!! 这就是你拥有的属性。使readyplayer成为实例变量,为它声明一个属性并使用synthesize。现在将alloc更改为:
[self setReadyPlayers: [NSMutableArray array]];
通过以下方式设置阅读器:
[self setReadyPlayers: [shufflePlayersFunction shufflePlayers: activePlayersArray]];
无需担心在dealloc等中释放您的数组。让操作系统为您执行容易出错的工作。 如果readyPlayers真的只是一个临时变量,请忘记alloc和release并让autorelease处理它。
[shufflePlayersFunction shufflePlayers: activePlayersArray]
应该返回一个自动释放的数组。
NSMutableArray *readyPlayers = [shufflePlayersFunction shufflePlayers: activePlayersArray];
NSLog(@"%@", readyPlayers);
// now forget about it