开发者

moving objects in nsmutablearray

i have an NSMutableArray;

NSMutableArray
--NSMutableArray
----NSDictionary
----NSDictionary
----NSDictionary
--NSMutableArra开发者_如何学Goy
----NSDictionary
----NSDictionary
----NSDictionary

i want to move first NSDictionary to second NSMutableArray. here is the code:

id tempObject = [[tableData objectAtIndex:fromSection] objectAtIndex:indexOriginal];
[[tableData objectAtIndex:fromSection] removeObjectAtIndex:indexOriginal];
[[tableData objectAtIndex:toSection] insertObject:tempObject atIndex:indexNew];

it removes the object but cant insert the object to new position. the error is:

[CFDictionary retain]: message sent to deallocated instance 0x4c45110

in header file:

NSMutableArray *tableData;
@property (nonatomic, retain) NSMutableArray *tableData;

how can i reorder/move the objects in nsmutablearray?


When an object is removed from a mutable array, it is send a release message. Thus, if nothing else holds references to it, the object will be deallocated.

So you can simply reorder the statements:

[[tableData objectAtIndex:toSection] insertObject:tempObject atIndex:indexNew];
[[tableData objectAtIndex:fromSection] removeObjectAtIndex:indexOriginal];

... or explicitly keep the object alive:

[tempObject retain];
[[tableData objectAtIndex:fromSection] removeObjectAtIndex:indexOriginal];
[[tableData objectAtIndex:toSection] insertObject:tempObject atIndex:indexNew];
[tempObject release];

Read through Array Fundamentals and Mutable Arrays for more details.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜