我有一些应该返回NSString的代码。相反,有时它返回一个NSArrayReverseEnumerator。这将导致无法识别的选择器发送到实例异常。
NSString *tFirstName = nil;
NSString *tUsername = ((NSString*)[self.userObject objectForKey:USER_NAME]).length > 0 ? [self.userObject objectForKey:USER_NAME] : [self.userObject objectForKey:USER_USERNAME];
NSRange spaceRange = [tUsername rangeOfString:@" "];
if (spaceRange.location == NSNotFound) {
tFirstName = tUsername;
} else {
tFirstName = [tUsername substringToIndex:spaceRange.location];
}
return tFirstName;
然后,我将UITextField文本属性设置为所返回的值,从而导致异常。
例外是:
-[__ NSArrayReverseEnumerator isEqualToString:]:无法识别的选择器已发送到实例0xf1b8190
这是堆栈跟踪的最后几行:
CoreFoundation 0x381208bf __exceptionPreprocess + 163
1 libobjc.A.dylib 0x31c061e5 objc_exception_throw + 33
2 CoreFoundation 0x38123acb -[NSObject doesNotRecognizeSelector:] + 175
3 CoreFoundation 0x38122945 ___forwarding___ + 301
4 CoreFoundation 0x3807d680 _CF_forwarding_prep_0 + 48
5 UIKit 0x354dc20d -[UILabel setText:] + 45
6 Trivial 0x000873c9 -[vcGameOver viewDidLoad] (vcGameOver.m:45)
7 UIKit 0x355117ff -[UIViewController view] + 167
userObject通常看起来像这样,尚未能够在调试器中进行再现,以查看异常时的外观:
userObject看起来像这样:
(PFUser *) $1 = 0x0be86fb0 <PFUser:MTsJR1DKuS> {
answeredCorrect = "<PFRelation: 0xa847f30>";
centsEarned = "-2353";
centsPaidFor = 5000;
centsUsed = 4193;
correctAnswers = 1454;
earnedCoinDate = "2012-06-12 19:42:44 +0000";
eloRating = 1262;
iq = 119;
lastPlayedDate = "2012-06-12 19:15:46 +0000";
locale = en;
losses = 10;
name = "Matt Hudson";
status = 0;
username = Inturbidus;
wins = 8;
wrongAnswers = 1157;
}
我的问题是,以上代码中的哪一行可能返回NSArrayReverseEnumerator?
最佳答案
您可能有一个悬空的指针,而其他对象(在这种情况下,大概是对Apple的__NSArrayReverseEnumerator
)蹲在内存中您过早释放的NSString
实例曾经所在的位置。
我建议打开僵尸(NSZombieEnabled
),看看是否收到“message sent to deallocated instance
”错误消息,而不是错误消息。