[英]how to add object at specified index in NSMutable array?
如何在指定索引處添加對象? 在我的問題上
NSMutableArray *substring
交替包含索引和對象,我需要根據從該數組獲取的索引將其添加到另一個數組str
。
NSMutableArray *str=[NSMutableArray new];
if ([substrings containsObject:@"Category-Sequence:"])
{
NSString *index=[substrings objectAtIndex:5];
//[substrings objectAtIndex:5]
gives me integer position at which I need to add object in `str` array,
gives 5,4,8,2,7,1 etc
NSString *object=[substrings objectAtIndex:1];
//[substrings objectAtIndex:1] gives object,gives NSString type of object
[str insertObject:object atIndex:(index.intValue)];
}
請提出一些實現它的方法。
提前致謝!
首先分配數組,然后嘗試在其中添加對象。
NSMutableArray *str = [[NSMutableArray alloc]init];
if ([substrings containsObject:@"Category-Sequence:"])
{
NSString *index=[substrings objectAtIndex:5];
NSString *object=[substrings objectAtIndex:1];
[str insertObject:object atIndex:(index.intValue)];
}
在將對象插入NSMutableArray
之前,先對其進行分配:
NSMutableArray *strMutableArray = [[NSMutableArray alloc] init];
(如果您不使用ARC,則還需要在完成后將其釋放。)
或者,如果不需要保留strMutableArray
,也可以使用一個臨時對象:
NSMutableArray *strMutableArray = [NSMutableArray array];
然后,您可以將對象插入NSMutableArray
。
但是,在不同數組中使用和的索引時要小心。 可能會有更好的方法來做您想要的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.