Fetch last five values from NSMutableArray

冷暖自知 提交于 2019-12-20 07:44:26

问题


I have a NSMutableArray whose count is 10 and I want to extract the last 5 values and store them in another array. How can I do this?


回答1:


I think that - (NSArray *) subarrayWithRange:(NSRange)range (doc) might help you.

NSRange theRange;
theRange.location = [wholeArray count] - 5;
theRange.length = 5;
NSArray *result = [wholeArray subarrayWithRange:theRange];

EDIT : Be careful to check that your array has at least five elements, else, subarrayWithRange will throw an exception.




回答2:


Use following way :

 NSMutableArray *first = [[NSMutableArray alloc] initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil];

    NSMutableArray *sec = [[NSMutableArray alloc] init];
    for(int i=5; i< [first count]; i++) {

        [sec addObject:[first objectAtIndex:i]];

     }

NSLog(@"sec - %@",sec);



回答3:


You can use subarrayWithRange method to get the desired arraydata. Try this hopefully it will work.

if (yourMutableArray.count > 10) 
{
NSArray *newArray = [yourMutableArray subarrayWithRange:NSMakeRange(yourMutableArray.count-10, yourMutableArray.count-1)];
}


来源:https://stackoverflow.com/questions/18457957/fetch-last-five-values-from-nsmutablearray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!