How to sort an array in iOS? - ios

i am newbie in iOS Development. My array Contain Dictionary Value Key like as
for(NSDictionary *dict in self.imageArray )
{
[self.imagesa addObject:#{#"demopage":[dict valueForKey:#"demopage"]}];
}
Here my "demoPage" Key Value Contain Two Key like as "link" and "Pageno" here link contain my ImageURL and "pageno" contain page number like as
-demopage
{
link:"URL",
page_no: "12"
},
{
link:"URL",
page_no: "13"
},
{
link: "URL",
page_no: "14"
},
{
link: "",
page_no: "3"
},
{
link:"URL",
page_no: "31"
},
{
link: "URL",
page_no: "32"
},
When i parsed it then i get data in This range like as 12,13,14,3,31,32 i want to arrange this image like as page number based i want it like as 1,2,3 up to data array.

For some reason you are storing the page number as a string and not a number. So a simple sort will sort it alphabetically.
i.e. 1, 10, 11, 12, 2, 20, 21, 235, 3, 35, 4
You need it to sort alphanumerically which you can do like this...
NSSortDescriptor *alphaNumSD = [NSSortDescriptor sortDescriptorWithKey:#"page_no" ascending:YES comparator:^(NSString *string1, NSString *string2) {
return [string1 compare:string2 options:NSNumericSearch];
}];
NSArray *sortedArray = [self.theArrayYouWantToSort sortedArrayUsingDescriptors:#[alphaNumSD]];
Example
NSArray *originalArray = #[
#{#"page_no": #"27"},
#{#"page_no": #"1"},
#{#"page_no": #"12"},
#{#"page_no": #"23"},
#{#"page_no": #"3"},
#{#"page_no": #"2"},
#{#"page_no": #"17"},
];
NSSortDescriptor *alphaNumSD = [NSSortDescriptor sortDescriptorWithKey:#"page_no"
ascending:YES
comparator:^(NSString *string1, NSString *string2)
{
return [string1 compare:string2 options:NSNumericSearch];
}];
NSArray *sortedArray = [originalArray sortedArrayUsingDescriptors:#[alphaNumSD]];
NSLog(#"%#", sortedArray);
Output
(
{
"page_no" = 1;
},
{
"page_no" = 2;
},
{
"page_no" = 3;
},
{
"page_no" = 12;
},
{
"page_no" = 17;
},
{
"page_no" = 23;
},
{
"page_no" = 27;
}
)
It definitely works as expected.

NSArray *ordersArray = info[#"result"];
NSArray *properSortedArray = [ordersArray sortedArrayUsingComparator:
^(id obj1, id obj2)
{
NSInteger value1 = [[obj1 objectForKey: #"orderId"] intValue];
NSInteger value2 = [[obj2 objectForKey: #"orderId"] intValue];
if (value1 > value2)
{
return (NSComparisonResult)NSOrderedAscending;
}
if (value1 < value2)
{
return (NSComparisonResult)NSOrderedDescending;
}
return (NSComparisonResult)NSOrderedSame;
}];

Try:
[self.dataArray sortedArrayUsingDescriptors:#[[NSSortDescriptor sortDescriptorWithKey:#"page_no" ascending:YES]]]

Related

Merging Two Arrays with Same Index in Objective C

I want to Merge Two Array With Same Index,
This is my JSON
"tier_info": [
{
"tier_id": "1",
"tier_name": "tier-1",
"price": "3.9",
"ios_id": "tier-1",
"android_id": "tier-1"
},
{
"tier_id": "2",
"tier_name": "tier-2",
"price": "4.9",
"ios_id": "tier-2",
"android_id": "tier-2"
},
{
"tier_id": "3",
"tier_name": "tier-3",
"price": "5.9",
"ios_id": "tier-3",
"android_id": "tier-3"
},
{
"tier_id": "4",
"tier_name": "free",
"price": "0",
"ios_id": "free",
"android_id": "free"
}
]
I'm using custom picker, Now I want "tier_name" with "price" in same array index [e.g. "tier_1 : 3.9"].
Code of merging two Array:
NSMutableArray *tierTitles = [[NSMutableArray alloc] init];
tierTitles = [tierArray valueForKey:#"tier_name"];
NSMutableArray *tierPrice = [[NSMutableArray alloc] init];
tierPrice = [tierArray valueForKey:#"price"];
NSMutableArray *combined = [[NSMutableArray alloc] init];
for (NSUInteger i = 0; i < tierArray.count; i++) {
[combined addObject: #{tierTitles[i]:tierPrice[i]}];
}
and i got this
(
{
"tier-1" = "3.9";
},
{
"tier-2" = "4.9";
},
{
"tier-3" = "5.9";
},
{
free = 0;
}
)
i want it like :
(
"tier-1" = "3.9";
"tier-2" = "4.9";
"tier-3" = "5.9";
free = 0;
)
what am i doing wrong here..any correct way to do this?
I think what you're asking is you need an NSDictionary that contains both name and price as key-value.You need to enumerate each object and add it to an array if the value exist :-
NSMutableArray *results=[NSMutableArray new];
for (NSDictionary *tier in tierArray]) {
if ([tier[#"tier_name"] length] && [tier[#"price"] length]) {
[results addObject:#{tier[#"tier_name"]:tier[#"price"]:}];
}
}
Or create a Mutable Dictionary Like this:-
NSMutableDictionary *results=[NSMutableDictionary new];
for (NSDictionary *tier in tierArray) {
if ([tier[#"tier_name"] length] && [tier[#"price"] length]) {
[results setValue:tier[#"price" forKey:tier[#"tier_name"]];
}
}
I think you should add dictionary to your combined array like as below
[tierTitles enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSMutableDictionary*combinedDict = [[NSMutableDictionary alloc]init];
[combinedDict setValue:[tierPrice objectAtIndex:idx] forKey:obj];
[combined addObject: combinedDict];
}];

IOS Compare two array and get Result

I have below JSON Format:
{
"Get_your_story_answer": [
{
"st_id": "19",
"story_title": "Newone",
"user_fb_id": "1649424812005217",
"winner_fb_id": "1685417121693688",
"winner_fb_id2": "",
"winner_fb_id3": "",
"story": "\ud83d\ude33\ud83d\ude25\ud83d\ude14\ud83d\ude0c",
"status": "1",
"s_created_date": "2016-01-18 23:06:05",
"reply_answer": [
{
"l_id": "42",
"story_id": "19",
"user_fb_id": "1649424812005217",
"selected_user_fb_id": "1685417121693688",
"answer": "hahaha",
"l_rating": "0",
"status": "1",
"l_created_date": "2016-01-18 23:10:51",
"l_new_created_date": "2016-01-19 11:40:51",
"winner": "1",
"answer_user_id": "3",
"answer_fb_id": "1685417121693688",
"answer_user_name": "Kin Patty"
},
{
"l_id": "43",
"story_id": "19",
"user_fb_id": "1649424812005217",
"selected_user_fb_id": "1498304680499454",
"answer": "",
"l_rating": "0",
"status": "1",
"l_created_date": "2016-01-18 23:06:05",
"l_new_created_date": "2016-01-19 11:36:05",
"winner": "0",
"answer_user_id": "10",
"answer_fb_id": "1498304680499454",
"answer_user_name": "John Kingman"
}
]
}
],
"status": "1",
"msg": "Get data"
}
Now I have to get Winner id
for Example "winner_fb_id" from [Get_your_story_answer] and compare it with [reply_answer].
If [reply_answer] contain "winner_fb_id" then I have to take only that name as winner .
Like in my Example , "Kin Patty"
I have tried this ,
//_getwind is mutable array
_getwinnerid =[NSMutableArray new];
_getwinnerid=[[_dataDictionary valueForKey:#"Get_your_story_answer"]valueForKey:#"winner_fb_id"];
Here is _getwinnerid output
<__NSArrayI 0x7ffb5a57c7b0>(
1685417121693688
NSArray *replaydata=[[_dataDictionary valueForKey:#"Get_your_story_answer"]valueForKey:#"reply_answer"];
Here is Replay Data Result
if (![replaydata containsObject:_getwinnerid]) {
NSLog(#"data");
}
Note:- Winner Id will be multiple. so, I have to compare 2 or more winner id and then take name from replay data response. And then I have to set name of winner in UITableview.
The value of Get_your_story_answer is an array, the requested data is in the first item of the array
NSDictionary *getYourStoryAnswer = _dataDictionary[#"Get_your_story_answer"][0];
Now get the winner ID and the array of answers
NSString *winnerID = getYourStoryAnswer[#"winner_fb_id"];
NSArray *answers = getYourStoryAnswer[#"reply_answer"];
Then enumerate the answers array (there are other solutions using blocks etc.)
for (NSDictionary *answer in answers) {
if ([answer[#"answer_fb_id"] isEqualToString: winnerID]) {
NSLog(#"%#", answer[#"answer_user_name"]);
break;
}
}
PS: Never use valueForKey to get one value for a key from a collection type unless you really need (and mean) the KVC method. The designated method is objectForKey or key subscription like above. valueForKey applied to an array returns always an array which is normally not intended.
for this you need to get total winner count from server.
like this.
int winnerCount = 3; //[Get_your_story_answer valueForKey:#"winner_count"];
Hopefully you have a fixed pattern key for winners like winner_fb_id, winner_fb_id1, winner_fb_id2 etc.
This will give you the desired result of winners name in array.
id response; // your response here
NSArray *array = [response objectForKey:#"Get_your_story_answer"];
NSDictionary *Get_your_story_answer = array[0];
NSMutableArray *winnersArray = [[NSMutableArray alloc] init];
int winnerCount = 3; //[Get_your_story_answer valueForKey:#"winner_count"];
for (int i = 0; i< winnerCount; i++) {
NSString *winnerId = nil;
if(i != 0){
winnerId = [Get_your_story_answer valueForKey:[NSString stringWithFormat:#"winner_fb_id%d",i]];
}
else{
winnerId= [Get_your_story_answer valueForKey:[NSString stringWithFormat:#"winner_fb_id"]];
}
if(winnerId)
{
[winnersArray addObject:winnerId];
}
}
__block NSMutableArray *resultArray = [[NSMutableArray alloc] init];
NSArray *replyAnswers = [Get_your_story_answer objectForKey:#"reply_answer"];
[replyAnswers enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
NSString *answer_fb_id = [obj valueForKey:#"answer_fb_id"];
[winnersArray enumerateObjectsUsingBlock: ^(NSString * winnerId, NSUInteger idx, BOOL *stop) {
if([winnerId isEqualToString:answer_fb_id]){
// get name of winner
[resultArray addObject:[obj valueForKey:#"answer_user_name"]];
}
}];
}];
// Your name of wiiners are in resultArray.
I have filtered array using the answer as said by larme Thank you.
NSError *errorJSON = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&errorJSON];
if (!errorJSON)
{
NSDictionary *storyAnwser = [json[#"Get_your_story_answer"] firstObject];
NSArray *allAnswersKeys = [storyAnwser allKeys];
NSArray *allWinnersKeys = [allAnswersKeys filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSString * _Nonnull evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
return [evaluatedObject hasPrefix:#"winner_fb_id"];
}]];
NSLog(#"AllWinnersKeys: %#", allWinnersKeys);
NSArray *allWinnersIds = [storyAnwser objectsForKeys:allWinnersKeys notFoundMarker:[NSNull null]];
NSLog(#"AllWinnersIds: %#", allWinnersIds);
NSArray *allAnswers = storyAnwser[#"reply_answer"];
NSLog(#"AllAnswers: %#", allAnswers);
NSArray *allWinners = [allAnswers filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"answer_fb_id IN %#", allWinnersIds]];
NSLog(#"allWinners: %#", allWinners);
NSArray *allWinersNames = [allWinners valueForKey:#"answer_user_name"];
NSLog(#"AllWinnersNames: %#", allWinersNames);
}
else
{
NSLog(#"Error JSON: %#", errorJSON);
}

How to Arrange JSON Parsed Array Based On Page Number?

i am newbie in iOS Development i parsed my JSON Data my Data like as
{
mid: "1",
name: "august 2014",
front_image:"http://www.truemanindiamagazine.com/webservice/magazineimage/frontimage/1.jpg",
title: "August fist edition",
release_date: "2014-08-01",
short_description: "Here we present to you for the first time our Magazine Trueman India. “Trueman India” covers Bollywood Gossips, film reviews, upcoming movies, F",
current_issue: 0,
-demopage: [
{
link:my image URL
page_no: "1"
},
{
link: my image URL,
page_no: "16"
},
{
link: my image URL,
page_no: "2"
},
{
link: my image URL,
page_no: "22"
},
{
link: my image URL,
page_no: "25"
},
{
link: my image URL,
page_no: "26"
},
And i parsed this Data into two array like as
NSError* error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
self.imagesa= nil;
if([jsonDict count]>0)
{
NSArray *arrData = [jsonDict objectForKey:#"data"];
if([arrData count]>0)
{
NSDictionary *imgDict = [arrData objectAtIndex:1];
if([imgDict count]>0)
{
NSMutableArray *imgsLinkArray = [imgDict objectForKey:#"demopage"];
self.imagesa = imgsLinkArray;
}
}
}
then it is Parsed and i got aresult what i want but here one problem is taht when i Show this image with Page number in Scrollview then i Show my image in to as per i got JSON data but i want my Imageview are Based on PageNumber like as From 1 to upto the data array Size.please Give me Solution for that i arrange my Image Based on my page number Wise here my Code for image and Page Number Parsing is
for(int index=0; index < [self.imagesa count]; index++)
{
NSDictionary *dict=[self.imagesa objectAtIndex:index];
NSString *image=[dict valueForKey:#"link"];
NSString *pageNumber=[dict valueForKey:#"page_no"];
smallImage = [[UIImageView alloc] init];
pageLabel=[[UILabel alloc]init];
[pageLabel setBackgroundColor:[UIColor clearColor]];
[smallImage sd_setImageWithURL:[NSURL URLWithString:image] placeholderImage:[UIImage imageNamed:#"1.png"]];
[pageLabel setText:[NSString stringWithFormat:#"Page%#",pageNumber]];
and i added my label and imageview into my Scrollview then it is Working as i want but it is not Show image Based on Page nuber like as From ! to upto array size please Give me Solution for that.
Sort your imagesLinkArray this way:
self.imagesa = [[imgsLinkArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([obj1[#"page_no"] intValue] > [obj2[#"page_no"] intValue]) {
return NSOrderedDescending;
} else if ([obj1[#"page_no"] intValue] < [obj2[#"page_no"] intValue]) {
return NSOrderedAscending;
}
return NSOrderedSame;
}] mutableCopy];
You should set the pageLabel test based on your index variable (+1), not the pageNumber. As follows:
[pageLabel setText:[NSString stringWithFormat:#"Page %lu",(long unsigned)(index+1)]];
Bro you drop value in An array Like this
if([imgDict count]>0)
{
NSMutableArray *imgsLinkArray = [imgDict objectForKey:#"demopage"];
self.imagesa = imgsLinkArray;
}
Then you have all the value in self.imagesa array....
So just wright only this....
[pageLabel setText:[NSString stringWithFormat:#"Page %lu",(long unsigned)[[self.imagesa objectAtIndex:index] valueForKey:#"page_no"]]];
For your short array OrderBy ............
NSMutableArray *recent=[[NSMutableArray alloc]init];
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"page_no" ascending:YES selector:#selector(localizedStandardCompare:)] ;
[self.imagesa sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
recent = [[self.imagesa sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]] copy];
self.imagesa = (NSMutableArray *) [[NSMutableArray alloc]initWithArray:recent];

How to get JSON response array all index values?

I need to get JSON response array all indexes values and maintain separate array. Here below I have posted my JSON response and I wanted to get console output looks like below also. Please help me.
response : [ {
A = [ {
name : "sons";
age = [
4
];
},
{
name : "rondo";
age = [
2
];
},
];
} ]
I need to store separate array separate values looks like below console output
2014-09-18 10:24:39.461 Myapp[1133:60b] RESULT : {
name = "sons";
age = 4;
}
2014-09-18 10:24:39.462 Myapp[1133:60b] RESULT : {
name = "rondo";
age = 2;
}
Here below I tried but I Know I can get only 0th index value but I need to get all index value from JSON response array:
myvalue = [NSString stringWithFormat:#"%#",[[[[responsData objectAtIndex:0] valueForKey:#"A"] objectAtIndex:0] valueForKey:#"name"]];
if you want to get all objects, get the array using the respective key.Then store the result in another array by iterating the for loop according to array count.
NSArray *recordsArr = [[responsedata objectAtIndex:0] valueForKey:#"A"];
NSMutableArray *resultArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [recordsArr count]; i ++) {
NSMutableDictionary *recordDict = [[NSMutableDictionary alloc] init];
[recordDict setObject:[[recordsArr objectAtIndex:i] valueForKey:#"name"] forKey:#"name"];
[recordDict setObject:[[[recordsArr objectAtIndex:i] valueForKey:#"age"] objectAtIndex:0] forKey:#"age"];
[resultArray addObject:recordDict];
}
NSLog(#"%#",resultArray);
output:
2014-09-18 12:49:22.047 testprj[1044:60b] (
{
age = 4;
name = sons;
},
{
age = 2;
name = rondo;
}
)
NSString *strName = (NSString *) [yourArray valueForKey:#"name"];
NSInteger age = [(NSNumber *) [yourArray valueForKey:#"age"] integerValue];

create array which is filtered from array of dictionary with the array as a input

I have one dictionary and one array as shown below
Dictionary :
{
"value": [
{
"ctgid": "1",
"catename": "tow"
},
{
"ctgid": "2",
"catename": "towrequest"
},
{
"ctgid": "3",
"catename": "electrical"
},
{
"ctgid": "5",
"catename": "plumber"
},
{
"ctgid": "6",
"catename": "maintenance"
},
{
"ctgid": "7",
"catename": "home"
},
{
"ctgid": "8",
"catename": "computer"
},
{
"ctgid": "9",
"catename": "1q2w"
}
]
}
Array of catename:
(
tow,
towrequest,
plumber
)
There is a list of catename in Array.From above dictionary I want to create the array of ctgid related to catename in above array.
So my final output should be :
Array of catgid :
(
1,
2,
5
)
Note : I can do it with loop , but I don't want to use any loop.
//Json data
NSString *jsonString = #"{\"value\":[{\"ctgid\":\"1\",\"catename\":\"tow\"},{\"ctgid\":\"2\",\"catename\":\"towrequest\"},{\"ctgid\":\"3\",\"catename\":\"electrical\"},{\"ctgid\":\"5\",\"catename\":\"plumber\"},{\"ctgid\":\"6\",\"catename\":\"maintenance\"},{\"ctgid\":\"7\",\"catename\":\"home\"},{\"ctgid\":\"8\",\"catename\":\"computer\"},{\"ctgid\":\"9\",\"catename\":\"1q2w\"}]}";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
//Converting the data into NSDictionary
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//Get the array of objects
NSArray *array = [NSArray arrayWithArray:[json objectForKey:#"value" ]];
//Category filter names
NSArray *filteCatename = [NSArray arrayWithObjects:#"tow",#"towrequest",#"plumber",nil];
//NSPreicate to filter the array using "in" constrain
NSArray *filtered = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"(catename in %#)", filteCatename]];
You can use NSPredicate to filter the NSArray directly without loop.
it is too late, though i put an answer hope this could help ..
[dictArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { //dictArray is an array contains your "value"
if([arrCatename containsObject:[obj objectForKey:#"catename"]]) //arrCatename is array contains catename list
{
[arrCatid addObject:[obj objectForKey:#"ctgid"]]; //arrCatid is the result
}
}];
NSLog(#"%#",arrCatid.description);
I haven't tested , but hopefully this is it .
NSMutableArray *arrCatID = [NSmutableArray alloc]init];
for (NSDictionary *instance in myDictionary){ // myDictionary is the values of "Value"
NSString *content = [instance objectForKey:#"catename"];
for (NSString *catName in stringArray) { // stringArray --> has already the CatNAmes with you
if (catName == content) {
[arrCatID addObject:[instance objectForKey:#"ctgid"];
break;
}
}
}

Resources