如何将NSMutableArray节对象索引值替换?

时间:2015-09-04 12:55:36

标签: ios objective-c

这是我的数组

(
        (
        3,
        3,
        3
    ),
        (
        2
    ),
        (
        1,
        1,
        1,
        1,
        1,
        1,
        1
    )
)

我想替换节对象值 使用以下代码

 [[sectionarray[indexPath.section] objectAtIndex:indexPath.row]replaceObjectAtIndex:indexPath.row withObject:@"0"];

例如

[[sectionarray[0] objectAtIndex:1]replaceObjectAtIndex:1 withObject:@"4"];

但是应用程序崩溃了,我得到的错误是

-[__NSCFConstantString replaceObjectAtIndex:withObject:]: unrecognized selector sent to instance 0x9a218 

如何替换数组部分对象值?

2 个答案:

答案 0 :(得分:1)

您在数组内的对象上调用replaceObjectAtIndex,而不是在数组本身上调用。这应该有效:

[[sectionarray[indexPath.section] replaceObjectAtIndex:indexPath.row withObject:@"0"];

答案 1 :(得分:1)

你将另一个级别嵌入到对象中。

( ( 3, 3, 3 ), ( 2 ), ( 1, 1, 1, 1, 1, 1, 1 ) )

让我们做你的代码解剖:

NSMutableArray *array = sectionarray[indexPath.section]; //gives you an array.
id obj = [array objectAtIndex:indexPath.row] //give you the strings 3, 3, 3, 2, 1, 1,1 

你在字符串上调用replace

[obj replaceObjectAtIndex:indexPath.row withObject:@"0"];

解决方案:您应该执行以下操作:

//First get the array at that section
NSMutableArray *arrayAtSection = sectionarray[indexPath.section];
//Now replace the object
[arrayAtSection replaceObjectAtIndex:indexPath.row withObject:@"0"];

以你的编码方式写作是:

[sectionarray[indexPath.section] replaceObjectAtIndex:indexPath.row withObject:@"0"];