gpt4 book ai didi

iphone - 尝试获取 UISegmentedControl 的 selectedSegmentIndex 时出现 EXC_BAD_ACCESS

转载 作者:行者123 更新时间:2023-11-28 22:53:33 26 4
gpt4 key购买 nike

我正在以编程方式将 UISegmentedControl 添加到我的 UINavigationBar,如下所示

UISegmentedControl *toggleSwitch = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects: @"Bar", @"Scatter", nil]];
toggleSwitch.segmentedControlStyle = UISegmentedControlStyleBar;
[toggleSwitch addTarget:self action:@selector(toggleSwitched:) forControlEvents:UIControlEventValueChanged];

UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithCustomView:toggleSwitch];
self.navigationItem.rightBarButtonItem = buttonItem;
[toggleSwitch release];
[buttonItem release];

然后我有一个方法 toggleSwitched 来处理事件:

-(void) toggleSwitched:(id) sender {
if([sender isKindOfClass:[UISegmentedControl class]]) {
NSLog(@"%@",((UISegmentedControl*)sender).selectedSegmentIndex );
}
}

来 self 对 Apple Documentation 的阅读,这是为触摸事件设置事件处理的正确方法。

但是,当我运行程序(在模拟器中)并点击段时,会发生以下情况:

  1. 如果它是第一个段(索引 0),“null”将记录到控制台
  2. 如果是第二段(索引 1),程序会崩溃并显示 EXC_BAD_ACCESS

当我查看调试器的变量窗口时,sender 是 UISegmentedControl 类型并且 _selectedSegment 属性似乎是正确的(0 或 1)。

我不正确地访问了什么?我如何设置我的委托(delegate)函数以在 UISegmentedController 的两个值之间切换?

最佳答案

你的 NSLog 是错误的。 selectedSegmentIndex 返回 NSUInteger,因此您需要使用 @"%d" 而不是 @"%@"%@ 用于对象,因此系统试图将数字用作指向对象的内存地址,并为您生成错误。

关于iphone - 尝试获取 UISegmentedControl 的 selectedSegmentIndex 时出现 EXC_BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11298788/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com