Value stored during its initialization is never re

2019-05-15 00:26发布

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.

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.

1条回答
我命由我不由天
2楼-- · 2019-05-15 00:50
Game *newGame = [[Game alloc] init];//error 1

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

newGame = [gamesArray objectAtIndex:gameNumber];

You obtain another instance from gamesArray and 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.

[newGame release];//error 2

At this point newGame points 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.

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

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

查看更多
登录 后发表回答