gpt4 book ai didi

objective-c - 替换对象索引 :withObject does not work

转载 作者:行者123 更新时间:2023-12-02 22:37:47 24 4
gpt4 key购买 nike

我正在尝试使用这段代码在 NSMutableArray 中分配对象

- (IBAction)variablePressed:(UIButton *)sender {
NSString *variable = [sender currentTitle];
if (!_variableToBePassedIntoTheDictionary) _variableToBePassedIntoTheDictionary = [[NSMutableArray alloc] init];
[_variableToBePassedIntoTheDictionary replaceObjectAtIndex:0 withObject:variable];}

但是当我运行这个程序时,程序在最后一行中断,因为我已经将调试器设置为在引发异常时显示警告。在没有断点的情况下运行程序,程序发出 SIGARBT 并崩溃。然后,我将这些值分配给一个字典,该字典将传递给模型以供进一步计算。

- (IBAction)testVariableValues:(id)sender {
if (!_variablesAssignedInADictionary) _variablesAssignedInADictionary = [[NSMutableDictionary alloc] init];
[_variablesAssignedInADictionary setObject:_digitToBePassedIntoTheVariable forKey:_variableToBePassedIntoTheDictionary];
NSLog(@"%@", _variablesAssignedInADictionary);}

附言我是 Objective C 的新手,谁能解释一下我们什么时候使用

@synthesize someProperty;

对比

@synthesize someProperty = _someProperty;

谢谢!

最佳答案

第一次调用该方法时,您创建了 NSMutableArray,然后尝试替换不存在的对象。引用资料说:

- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject

The index of the object to be replaced. This value must not exceed the bounds of the array. Important Raises an NSRangeException if index is beyond the end of the array.

0 将超出空数组的边界。

试试这个:

- (IBAction)variablePressed:(UIButton *)sender
{
NSString *variable = [sender currentTitle];
if (_variableToBePassedIntoTheDictionary == nil)
{
_variableToBePassedIntoTheDictionary = [[NSMutableArray alloc] init];
[_variableToBePassedIntoTheDictionary addObject:variable];
}
else
{
[_variableToBePassedIntoTheDictionary replaceObjectAtIndex:0 withObject:variable];
}
}

关于objective-c - 替换对象索引 :withObject does not work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11178010/

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