Xcode 在初始化期间存储的值永远不会被读取
我正在尝试创建一个游戏,以便我可以更改其数据并将其保存回去。我在注释行中得到两个错误。为什么我会犯这些错误。我分配了游戏,所以我必须正确地发布它。这是我保存游戏的代码Xcode 在初始化期间存储的值永远不会被读取,xcode,memory-leaks,initialization,reference-counting,Xcode,Memory Leaks,Initialization,Reference Counting,我正在尝试创建一个游戏,以便我可以更改其数据并将其保存回去。我在注释行中得到两个错误。为什么我会犯这些错误。我分配了游戏,所以我必须正确地发布它。这是我保存游戏的代码 Game *newGame = [[Game alloc] init];//error 1 newGame = [gamesArray objectAtIndex:gameNumber]; [newGame setTheShotArray:shotArray]; [gamesArray replaceObjectAtIndex:g
Game *newGame = [[Game alloc] init];//error 1
newGame = [gamesArray objectAtIndex:gameNumber];
[newGame setTheShotArray:shotArray];
[gamesArray replaceObjectAtIndex:gameNumber withObject:newGame];
NSString *path = [self findGamesPath];
[NSKeyedArchiver archiveRootObject:gamesArray toFile:path];
[newGame release];//error 2
我得到了错误1,它表示在初始化过程中存储到“newGame”的值从未被读取
第二个错误表示调用方此时不拥有的对象的引用计数减少不正确
这是什么意思?请不要告诉我,你需要阅读有关内存管理的内容,然后给我一个链接。请告诉我如何解决这个问题
Game *newGame = [[Game alloc] init];//error 1
您创建了一个新实例并拥有它,因为您使用了+alloc
newGame = [gamesArray objectAtIndex:gameNumber];
您可以从gamesArray
获取另一个实例,并将其分配给上一行中使用的同一个变量。这意味着您丢失了对上一个对象的引用,并且由于您拥有上一个对象,因此您有责任释放它。你没有,所以你把那个东西漏掉了
[newGame release];//error 2
此时,newGame
通过fromgamesArray
指向实例。您没有拥有它,因为您没有通过NARC获得它,因此您不应该发布它
NARC:一种方法,其名称包含new
、alloc
、copy
,或是retain
一句话:你正在泄漏你通过
+alloc
创建的对象,并且你试图释放一个你不拥有的对象。游戏的基类是什么?你在游戏中使用cocos2d吗?