ios - Looping thru NSArray of NSString logic -
i need help following:
i have nsarray nsstrings, want loop thru these strings , find matching string, when match found strings after match extracted nsdictionary until other match hit.
here example:
nsarray *array = @[@"fruit",@"apple",@"vegtable",@"tomato",@"fruit",@"banana",@"vegtable",@"cucumber"];
so want loop thru array , split in 2 arrays 1 fruit , 1 vegetable.
anyone can help logic?
thanks
this simplest way solve problem:
nsarray *array = @[@"chair",@"fruit",@"apple",@"orange",@"vegetable",@"tomato",@"fruit",@"banana",@"vegetable",@"cucumber"]; nsmutablearray *fruitarray = [nsmutablearray array]; nsmutablearray *vegetablearray = [nsmutablearray array]; nsmutablearray *currenttarget = nil; (nsstring *item in array) { if ([item isequaltostring: @"fruit"]) { currenttarget = fruitarray; } else if ([item isequaltostring: @"vegetable"]) { currenttarget = vegetablearray; } else { [currenttarget addobject: item]; } }
in 1 iteration on array, maintain adding items result array using pointer 1 of 2 result arrays according lastly occurrence of @"fruit"
or @"vegetable"
string.
this algorithm ignores items before first occurrence of @"fruit"
or @"vegetable"
string, because currenttarget
initialized nil
, ignores addobject:
messages. if want different behaviour, alter initialization.
you said wanted results in nsdictionary, didn't specify should key. if want 1 nsdictionary 2 keys, fruit , vegetable, , values nsarrays containing items, utilize arrays created:
nsdictionary *dict = @{ @"fruit": fruitarray, @"vegetable": vegetablearray };
ps: have typo in example, vegtable instead of vegetable. corrected in code, maintain in mind.
ios objective-c nsstring nsarray
No comments:
Post a Comment