【问题标题】:NSString IntValue exception when parsing notification userInfo解析通知userInfo时出现NSString IntValue异常
【发布时间】:2015-03-11 15:41:06
【问题描述】:

我正在实现一个登录系统,它使用NSNotifications userInfo 字典通过通知传递登录信息。字典可以通过,但是当我尝试使用 IntValue 将字典中的 NSStrings 之一转换为 int 时,出现错误。即使当我将字典对象复制到另一个字符串时,我也会收到相同的错误,但使用普通字符串时不会出现错误。代码:

- (void)loginComplete:(NSNotification *) notification {
    if ([[notification name] isEqualToString:@"Login Complete"]) {
        NSDictionary *loginInfo = [notification userInfo];

        loginString = [loginInfo objectForKey:@"login_string"];
        NSLog(@"%@", loginString);
        NSString* expString = [NSString stringWithString:[loginInfo objectForKey:@"expires_in"]];
        // [loginInfo objectForKey:@"expires_in"] == @"604700"
        expiresIn   = [expString intValue];
        NSLog(@"expiresIn: %i", expiresIn);

        NSString * toInt = @"112345";
        int realInt = [toInt intValue];
        NSLog(@"realInt: %i", realInt);
    }
}

所以第一个NSLog 提供了正确的信息,最后(测试)的转换也可以,但是 expiresIn 导致错误:

2015-01-13 17:53:06.976 API_test_osx[2867:143430] -[__NSArrayM length]: unrecognized selector sent to instance 0x600000441d40
2015-01-13 17:53:06.976 API_test_osx[2867:143430] *** WebKit discarded an uncaught exception in the webView:didFinishLoadForFrame: delegate: <NSInvalidArgumentException> -[__NSArrayM length]: unrecognized selector sent to instance 0x600000441d40

如果我尝试不转换为 int,则该值可以很好地记录为 NSString。我做错了什么?

【问题讨论】:

标签: objective-c cocoa nsnotificationcenter


【解决方案1】:

您认为是NSString 的对象实际上是NSArray,如错误消息所示:

-[__NSArrayM length]: unrecognized selector sent to instance 0x600000441d40

我无法提供更多信息,除此之外,如果您在 Objective-C 集合类中传递整数,则使用 NSNumber 对象,而不是 NSString 对象。

【讨论】:

  • 有道理,谢谢。我使用的第三方代码将值制成长度为 1 的数组。让我无法理解的是,我仍然能够将值分配给 NSString ivars,这可能是因为它隐式调用了 NSArrays toString 方法。我将您的答案标记为正确的。
  • 也更喜欢使用 'NSInteger' 而不是 'int' 和 'integerValue' 而不是 'intValue'
【解决方案2】:

看起来您正在访问您指定的键下的对象数组。您还需要访问对象索引值。即objectAtIndex。希望这会有所帮助

【讨论】:

  • 是的,现在就这样做。谢谢。
猜你喜欢
  • 2018-08-11
  • 1970-01-01
  • 2011-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-25
  • 2018-03-06
  • 1970-01-01
相关资源
最近更新 更多