我目前很困惑为什么以下情况在某些情况下有效,但在其他情况下无效。使用以下代码时:
NSString *currentLoc = [[NSString stringWithString:sceneName] retain];
self.currentLocation = currentLoc;
[currentLoc release];
NSString *currentLocation, of type (nonatomic, retain)
这应该用新值覆盖 my 。为什么我现在不能通过执行以下操作来访问此值:
NSString *test = currentLocation;
调试时,我看到 test 设置为随机数组,因此指针必须指向完全不同的东西。我已经检查了代码,并且 currentLocation 变量仅在此处设置。如果我使用以下内容:
NSString *test = self.currentLocation;
然后现在显示正确的值,有人可以解释为什么 currentLocation / self.currentLocation 被视为不同的对象,我理解那个自我。使用访问器,但如果设置正确,它们肯定都应该指向相同的值?
编辑1:(所有代码)
。H
NSString *currentLocation;
@property (nonatomic, retain) NSString *currentLocation;
.m
@synthesize currentLocation;
NSString *currentLoc = [[NSString stringWithString:sceneName] retain];
self.currentLocation = currentLoc;
[currentLoc release];
if (currentLocation != nil && singleton.storyLocation != nil)
{
if (boolMoviePlayed == false && [singleton.storyLocation isEqualToString:currentLocation]) // crash here due to current location being set to an array
[buttonPlayMovie setHidden:!textVisible];
}
self.currentLocation = nil; // viewDidUnload
[currentLocation release]; // dealloc
编辑2:(更新代码,仍然崩溃)
所以这次我尝试按照设置的方式访问代码,如下所示:
if (self.currentLocation != nil && singleton.storyLocation != nil)
{
if (boolMoviePlayed == false && [singleton.storyLocation isEqualToString:self.currentLocation])
[buttonPlayMovie setHidden:!textVisible];
}
但是,这一次我遇到了一个变量似乎未设置的崩溃,即使它在此过程中的任何时候都没有更改(参见 EDIT 1 中的代码)。
编辑 3:
现在我很困惑,我以为我有答案,但我只是没有。我尝试使用 Erics 的建议:
@synthesize currentLocation = _currentLocation;
然后我确保所有对 currentLocation 的访问都是使用 self.currentLocation = xyz 设置的。现在谈到 dealloc 方法时,我总是被警告不要使用 self. 在交易中。但这意味着我所有的值都为零,因为 currentLocation 尚未设置。使用 [self.currentLocation release] 是否安全,或者如何解决我的问题?
编辑4:
据我所知,然后你在 dealloc 中使用 [_currentLocation release],如果我错了,请纠正我,如果不是,我现在会沿着这条路线走,因为它似乎有效。