【问题标题】:EXC_BAD_ACCESS on NSMutableDictionaryNSMutableDictionary 上的 EXC_BAD_ACCESS
【发布时间】:2013-02-02 15:34:37
【问题描述】:

我从 iOS 开发开始,我有这个代码:

首先我声明listOfItems NSMutableArray:

@interface SAMasterViewController () {
    NSMutableArray *listOfItems;
}
@end

现在,这里是给我“EXC_BAD_ACCESS (code=1, address=0x5fc260000)”错误的代码部分。 错误在“individual_data”对象的最后一行给出。

listOfItems = [[NSMutableArray alloc] init];
for(NSDictionary *tweetDict in statuses) {
    NSString  *text          = [tweetDict objectForKey:@"text"];
    NSString  *screenName    = [[tweetDict objectForKey:@"user"] objectForKey:@"screen_name"];
    NSString  *img_url       = [[tweetDict objectForKey:@"user"] objectForKey:@"profile_image_url"];
    NSInteger unique_id      = [[tweetDict objectForKey:@"id"] intValue];
    NSInteger user_id        = [[[tweetDict objectForKey:@"user"] objectForKey:@"id"] intValue ];

    NSMutableDictionary *individual_data = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                            text, @"text_tweet",
                                            screenName,@"user_name",
                                            img_url, @"img_url",
                                            unique_id, @"unique_id",
                                            user_id, @"user_id", nil];
    [listOfItems addObject:individual_data];
}

提前致谢。

【问题讨论】:

  • 你不应该在字典上调用 initWithCapacity:20 吗?
  • 其实应该用数字状态的容量来初始化。
  • 是的,我以 20 为例。你是对的

标签: iphone ios objective-c exc-bad-access nsmutabledictionary


【解决方案1】:

您不能将NSIntegers 或任何其他非Objective-C 类放在数组或字典中。您需要将它们包装在 NSNumber 中。

NSMutableDictionary *individual_data = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                            text, @"text_tweet",
                                            screenName,@"user_name",
                                            img_url, @"img_url",
                                            [NSNumber numberWithInteger:unique_id], @"unique_id",
                                            [NSNumber numberWithInteger:user_id], @"user_id", nil];
//Or if you want to use literals
NSMutableDictionary *individual_data = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                            text, @"text_tweet",
                                            screenName,@"user_name",
                                            img_url, @"img_url",
                                            @(unique_id), @"unique_id",
                                            @(user_id), @"user_id", nil];

【讨论】:

  • 这就是这里的目的。此外,如果[tweetDict objectForKey:@"id"] 返回NSNumber*,那么您应该将它们存储为NSNumber
  • 知道了,谢谢,我很高兴学习这门语言。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-23
  • 2015-03-13
  • 2012-03-05
  • 2021-04-02
  • 2016-09-13
相关资源
最近更新 更多