Objective-C尝试使用setString改变不可变对象:

时间:2015-04-26 18:01:15

标签: objective-c

我遇到了这个错误,我对Objective-C相当新:

我正在尝试运行此代码:

-(void)myCheckBoxCellDidChange:(MyCheckBoxCell *)checkBox {

    CellData *cellItem = _dataSourceHelper.data[checkBox.coordinate.row.rowIndex];

    if(([[cellItem actualDate] isEqualToString:@""]) && ([[cellItem finishedDate] isEqualToString:@""]))
    {
        [[cellItem actualDate]setString:[NSString stringWithFormat:@"%@ 8:00:00 AM",[self SetSpecialDateFormat:[NSDate date]]]];
        [[cellItem finishedDate]setString:[NSString stringWithFormat:@"%@ 4:00:00 PM",[self SetSpecialDateFormat:[NSDate date]]]];
    }

    cellItem.selected = [checkBox checked];

    [spreadSheet reloadRows:@[checkBox.coordinate.row]];
}

我在if条件下设置断点,下一行因此错误而崩溃:

  

尝试使用setString:

来改变不可变对象

为什么会发生这种情况,我该如何解决?

以下是SetSpecialDateFormat方法:

- (NSString *)SetSpecialDateFormat:(NSDate *)date
{

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    NSString *theDate = [dateFormat stringFromDate:date];
    dateFormat = nil;
    return theDate;
}

完整错误:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to mutate immutable object with setString:'
*** First throw call stack:
(0x26b2ffef 0x34ddfc8b 0x26b2ff35 0x26aeb26f 0xb3301 0xc33d9 0x2a30206b 0x2a1b10f9 0x2a5caf9b 0x2a17a181 0x2a17805f 0x2a1af4d9 0x2a1aeddd 0x2a184fe5 0x2a3fb8fb 0x2a1839f9 0x26af5faf 0x26af53bf 0x26af3a25 0x26a40201 0x26a40013 0x2e20d201 0x2a1e4a59 0xa75b1 0x3536baaf)
libc++abi.dylib: terminating with uncaught exception of type NSException`

enter image description here

这就是其他地方:

actualDate = [[NSMutableString alloc]init];

[[cellData actualDate]setString:@""];

[[cellData actualDate]setString:[object valueForKey:@"actualDate"]];

[formattedCell setActualDate:(NSMutableString*)([c.actualDate isEqualToString:@""]?@"":[self reverseStringDate:[c.actualDate substringToIndex:10]])];
-(NSString *)reverseStringDate:(NSString*)originalDateString
{
    NSArray* components = nil;
    components = [originalDateString componentsSeparatedByString:@"-"];
    NSString *reversedString = [NSString stringWithFormat:@"%@-%@-%@",[components objectAtIndex:2],[components objectAtIndex:1],[components objectAtIndex:0]];
    return reversedString;
}

1 个答案:

答案 0 :(得分:2)

[formattedCell setActualDate:(NSMutableString*)([c.actualDate isEqualToString:@""]?@"":[self reverseStringDate:[c.actualDate substringToIndex:10]])];

这是非常有问题的。你只是将任何这个长链垃圾链变成一个可变的字符串......而这只是不起作用。

首先,不需要所有这些无意义的。然后,让我们在mutableCopy对象上调用NSString,而不是强制转换,这样我们就可以获得NSMutableString个对象。

NSMutableString *dateString = [@"" mutableCopy];
if (![c.actualDate isEqualToString:@""]) {
    dateString = [[self reverseStringDate:[c.actualDate substringToIndex:10]] mutableCopy];
}

[formattedCell setActualDate:dateString];