我正在尝试创建一个动态的顶部菜单。 我必须从 json 请求中获取一些数据并将这些数据显示在顶部菜单的一个部分中。我是 Objective-C 的新手。我也尝试使用 NSMutableArrays,但出现错误。只有一个 MutableArray 和我可以显示顶部菜单。我正在关注顶级菜单的第三方框架“https://github.com/dopcn/DOPNavbarMenu” ”。
- (DOPNavbarMenu *)menu {
if (_menu == nil) {
[strArray objectAtIndex:0];
NSLog(@"Random Selection is:%@",strArray);
_menu = [[DOPNavbarMenu alloc] initWithItems:@[strArray] width:self.view.dop_width maximumNumberInRow:_numberOfItemsInRow];
_menu.backgroundColor = [UIColor blackColor];
_menu.separatarColor = [UIColor whiteColor];
_menu.delegate = self;
}
return _menu;
}
-(void)loadData
{
strResponse=[dictionary objectForKey:@"data"];
strMsg=[strResponse valueForKey:@"Text"];
NSLog(@“string message is :%@",strMsg);
NSLog(@"String Response is :%@",strResponse);
NSLog(@"Text Response is: %@",strMsg);
strArray = [[NSMutableArray alloc] init];
[strArray addObject:strMsg];
NSLog(@"Array values are - %@", strArray);
}
数组值是:生活方式、护理计划、跟踪器/日记、问卷/评估。
但是我遇到了这样的异常:
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object from objects[0]'
最佳答案
好的,根据您的意见
but i want to call menu method before loadData finishes
问题出在这里:
_menu = [[DOPNavbarMenu alloc] initWithItems:@[strArray] width:self.view.dop_width maximumNumberInRow:_numberOfItemsInRow];
在运行 loadData
之前,我假设 strArray
是 nil
。这导致这部分 @[strArray]
失败 - 这将创建一个新数组,其中 strArray
作为其唯一元素,不能为 nil
。
我还假设您希望在那里传递 strArray
本身,而不是将其包装在另一个数组中。
现在,如果您在 loadData
中填充 strArray
之前调用 menu
,菜单中可能不会出现任何项目,除非您有一种在 loadData
完成后用新项目更新它的方法。
总而言之:要解决您眼前的问题,您应该将上面的行更改为:
_menu = [[DOPNavbarMenu alloc] initWithItems:strArray width:self.view.dop_width maximumNumberInRow:_numberOfItemsInRow];
这应该有效,但由于上述原因,菜单中不会出现任何项目。
关于ios - 尝试从 objects[0] 中插入 nil object in objective-c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34202355/