xcode 永远不会读取在其初始化期间存储的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5762161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 20:53:32  来源:igfitidea点击:

Value stored during its initialization is never read

xcodememory-leaksinitializationreference-counting

提问by Blane Townsend

I am trying to create a Game so that I can change its data and save it back. I get two errors that are on the commented lines. Why am I getting these errors. I allocated the Game so I should have to release it correct. Here is my code to save my Game

我正在尝试创建一个游戏,以便我可以更改其数据并将其保存回来。我在注释行中收到两个错误。为什么我会收到这些错误。我分配了游戏,所以我应该正确地发布它。这是我保存游戏的代码

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

I get error 1 which says Value stored to 'newGame' during its initialization is never read.

我收到错误 1,表示在初始化期间存储到“newGame”的值永远不会被读取。

The second error says Incorrect decrement of the reference count of an object that is not owned at this point by the caller.

第二个错误表示调用者此时不拥有的对象的引用计数不正确递减。

What does this mean? And please don't tell me, you need to read up on memory management and just give me a link. Tell me how to fix the problem please.

这是什么意思?请不要告诉我,你需要阅读内存管理,然后给我一个链接。请告诉我如何解决问题。

回答by

Game *newGame = [[Game alloc] init];//error 1

You create a new instance and you own it since you've used +alloc.

您创建了一个新实例并拥有它,因为您已经使用了+alloc.

newGame = [gamesArray objectAtIndex:gameNumber];

You obtain another instance from gamesArrayand assign it to the same variable that was used in the previous line. This means that you've lost the reference to the previous object and, since you own the previous object, you're responsible for releasing it. You don't, so you're leaking that object.

您从中获取另一个实例 gamesArray并将其分配给前一行中使用的同一变量。这意味着您已经丢失了对前一个对象的引用,并且由于您拥有前一个对象,您有责任释放它。你没有,所以你正在泄漏那个对象。

[newGame release];//error 2

At this point newGamepoints to the instance via from gamesArray. You do not own it since you haven't obtained it via NARC, hence you should not release it.

此时newGame通过 from指向实例gamesArray。你不拥有它,因为你没有通过 NARC 获得它,因此你不应该释放它。

NARC: a method whose name contains new, alloc, copy, or is retain.

NARC:名称中包含的方法newalloccopy,或retain

Bottom line: you're leaking the object that you've created via +allocand you're trying to release an object that you do not own.

底线:您正在泄漏您通过它创建的对象,+alloc并且您正试图释放一个不属于您的对象。