Core Data Saving and Fetching - ios

I want to import these datas in CoreData framework with save and retrieve.can anyone please tell me how to implement this in CoreData Framework or some reference tutorial and please tell me how to save these datas in Entities.
JSON: {
Options = (
);
Questions = (
{
AssessmentId = 4;
QuestionDesc = "Below are five statements that you may agree or disagree with. Using the 1 - 7 scale below, indicate your agreement with each item by placing the appropriate number on the line preceding that item. Please be open and honest in your responding";
QuestionId = 18;
QuestionNo = 1;
QuestionTypeDesc = Rating;
QuestionTypeId = 3;
}
);
RankingOptions = (
);
RatingOptions = (
{
AnswerId = 1;
OptionDesc = "In most ways my life is close to my ideal. ";
OptionId = 1;
OptionValue = 1;
QuestionId = 18;
},
{
AnswerId = 2;
OptionDesc = "The conditions of my life are excellent.";
OptionId = 2;
OptionValue = 2;
QuestionId = 18;
},
{
AnswerId = 3;
OptionDesc = "I am satisfied with my life.";
OptionId = 3;
OptionValue = 3;
QuestionId = 18;
},
{
AnswerId = 4;
OptionDesc = "So far I have gotten the important things I want in life.";
OptionId = 4;
OptionValue = 4;
QuestionId = 18;
},
{
AnswerId = 5;
OptionDesc = "If I could live my life over, I would change almost nothing.";
OptionId = 5;
OptionValue = 5;
QuestionId = 18;
}
);
ResponseDetails = {
Msg = "DATA FOUND!";
ResultStatus = 1;
};
}

First you need to convert these json data into NSDictionary
NSError* error;
NSDictionary* inDictionary = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
Then save this NSDictionary into core data.
AppDelegate *sharedDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [sharedDelegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setReturnsObjectsAsFaults:NO];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"QestInfo"
inManagedObjectContext:context]; // Create an Entity in coredata "QestInfo" (use your entity name)
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:nil];
QestInfo * qestInfo = [NSEntityDescription
insertNewObjectForEntityForName:#"ThreadInfo"
inManagedObjectContext:context];
for (QestInfo *info in fetchedObjects)
{
if([[inDictionary allKeys] containsObject:#"userEmail"])
{
if([inDictionary valueForKey:#"userEmail"]!=[NSNull null])
{
qestInfo. AssessmentId =[inDictionary valueForKey:#"userEmail"];
}
}
.
.// Your key here
.
}
NSError *error;
if(![context save:&error]){
NSLog(#"SAVE ERROR");
}
Also check this http://www.raywenderlich.com/934/core-data-tutorial-for-ios-getting-started tutorial for beginners.

Related

NSDictionary Getting Repeated values

I know this may be a repeated question but I googled a lot but not able to find a suitable answer for me.
I have a NSMutableArray which has two NSDictionary with Keys and values which I need to populated on a UITableView. I have retrieved the value of the dictionary which I'm going populate using
NSMutableArray *mutArray = [responseArray valueForKey:#"Table"];
And I did like
NSMutableSet *names = [NSMutableSet set];
NSMutableArray *mutArray1 = [[NSMutableArray alloc] init];
for (id obj in mutArray) {
NSString *destinationName = [obj valueForKey:#"AssetClassName"];
if (![names containsObject:destinationName]) {
[mutArray1 addObject:destinationName];
[names addObject:destinationName];
}
}
Because the value AssetClassName is repeated. Now I have three values in mutArray1 which I need to show as UITableView section. Under AssetClassName I have Some data which determines the row in that section.
For retrieving that data I'm doing like
for (int i = 0; i < [mutArray1 count]; i++) {
NSMutableDictionary *a = [[NSMutableDictionary alloc] init];
NSMutableDictionary *b = [[NSMutableDictionary alloc] init];
for (NSDictionary *dict in mutArray) {
if ([[mutArray1 objectAtIndex:i] isEqualToString:[dict valueForKey:#"AssetClassName"]]) {
[a setObject:[dict objectForKey: #"SubAssetClassName"] forKey:#"Investment Categories"];
[a setObject:[dict valueForKey:#"Amount"] forKey:#"Amount (EUR)"];
[a setObject:[dict valueForKey:#"AllocationPercentage"] forKey:#"%"];
[a setObject:[dict valueForKey:#"ModelAllocationPercentage"] forKey:#"ModelAllocationPercentage"];
[b setObject:a forKey:[dict valueForKey:#"SubAssetClassName"]];
[mutdict setObject:b forKey:[dict valueForKey:#"AssetClassName"]];
}
}
}
mutdict is a NSMutableDictionary declared globally and is instantiate in viewdidLoad
mutdict = [[NSMutableDictionary alloc] init];
The values are inserted into mutdict as I needed. Each SubAssetClassName is added into AssetclassName accordingly.
But my problem is in my final dictionary i.e mutdict the values for SubAssetClassName is repeated.
Can anybody tell how to solve this.
My console
"AssetClassName" = {
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "HIGH YIELD BONDS";
"ModelAllocationPercentage" = 22;
};
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "HIGH YIELD BONDS";
"ModelAllocationPercentage" = 22;
};
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "HIGH YIELD BONDS";
"ModelAllocationPercentage" = 22;
};
};
"AssetClassName" = {
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "EMERGING MARKETS EQUITIES";
"ModelAllocationPercentage" = 10;
};
};
"AssetClassName" = {
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "STRUCTURED PRODUCTS";
"ModelAllocationPercentage" = 10;
};
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "STRUCTURED PRODUCTS";
"ModelAllocationPercentage" = 10;
};
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "STRUCTURED PRODUCTS";
"ModelAllocationPercentage" = 10;
};
};
}
Here I can see that all SubAssetClass values are same for each section but actually its not.
How can I solve this.
You need to create a new instance of your mutable dictionary inside the loop. Right now you create one instance and update it over and over. This results in one dictionary being added over and over.
Change you code as follows:
for (NSInteger i = 0; i < [mutArray1 count]; i++) {
NSMutableDictionary *b = [[NSMutableDictionary alloc] init];
for (NSDictionary *dict in mutArray) {
if ([[mutArray1 objectAtIndex:i] isEqualToString:[dict valueForKey:#"AssetClassName"]]) {
NSMutableDictionary *a = [[NSMutableDictionary alloc] init];
[a setObject:[dict objectForKey: #"SubAssetClassName"] forKey:#"Investment Categories"];
[a setObject:[dict valueForKey:#"Amount"] forKey:#"Amount (EUR)"];
[a setObject:[dict valueForKey:#"AllocationPercentage"] forKey:#"%"];
[a setObject:[dict valueForKey:#"ModelAllocationPercentage"] forKey:#"ModelAllocationPercentage"];
[b setObject:a forKey:[dict valueForKey:#"SubAssetClassName"]];
[mutdict setObject:b forKey:[dict valueForKey:#"AssetClassName"]];
}
}
}
Also, in most cases you should not be using valueForKey:. Use objectForKey: unless you have a clear and specific need to use key-value coding instead of simply getting an object from the dictionary for a given key.

How to sort this NSDictionary based on its key "id" ascending order?

Hi This is what am getting from server
{
1 = {
"display_name" = "One";
id = 1;
};
2 = {
"display_name" = "Two";
id = 2;
};
13 = {
"display_name" = "abc";
id = 13;
};
15 = {
"display_name" = "aaa";
id = 15;
};
4 = {
"display_name" = "ffd";
id = 4;
};
3 = {
"display_name" = "abdfdfc";
id = 3;
};
5 = {
"display_name" = "aasdfsdfa";
id = 5;
};
}
i need to sort this based on "id" this is what am looking as output
Expecting output
{
1 = {
"display_name" = "One";
id = 1;
};
2 = {
"display_name" = "Two";
id = 2;
};
3 = {
"display_name" = "abdfdfc";
id = 3;
};
4 = {
"display_name" = "ffd";
id = 4;
};
5 = {
"display_name" = "aasdfsdfa";
id = 5;
};
13 = {
"display_name" = "abc";
id = 13;
};
15 = {
"display_name" = "aaa";
id = 15;
};
}
This code i have tried and its not working
//vehiclesDictionary real dictionary
NSMutableArray *sortedKeys=[[NSMutableArray alloc]init];
for(NSString *item in [vehiclesDictionary allKeys]){
[sortedKeys addObject:[NSNumber numberWithInt:[item intValue]]];
}
NSArray *sortedKeysArray = [sortedKeys sortedArrayUsingSelector: #selector(compare:)];
NSLog(#"%#",sortedKeysArray);
NSMutableDictionary *sortedValues = [[NSMutableDictionary alloc] init];
for (NSString *key in sortedKeysArray) {
[sortedValues setValue:[vehiclesDictionary valueForKey:[NSString stringWithFormat:#"%#",key]] forKey:key];
}
NSLog(#"%#",sortedValues);
Pls help me
You cannot sort an NSDictionary, it is an unsorted collection type. You will need to store your keys in an array and sort this and use it to access the NSDictionary in order.
Based on your code above, it could be modified as follows, e.g.
NSDictionary *dict = [NSDictionary dictionary];
NSArray *sortedKeys = [[dict allKeys] sortedArrayUsingSelector:#selector(compare:)];
for (NSString *key in sortedKeys) {
NSLog(#"%#", [d objectForKey:key]);
// Do something with the object here
}
Here you can pass around the sortedKeys array with the NSDictionary, and use the sortedKeys array for in-order access to your NSDictionary.
A more concise approach to get the array, but with the same outcome as above, would be using:
NSDictionary -keysSortedByValueUsingComparator as shown here.
As others have mentioned, NSDictionaries cannot be sorted. However, you could do something like this:
-(NSArray *)sortedKeysFromDictionary:(NSDictionary *)dictionary ascending:(BOOL)ascending
{
/* get all keys from dictionary */
NSArray *allKeys = [dictionary allKeys];
NSString *key = #"id"; // using "id" as key here
/* sort keys */
NSSortDescriptor *dateDescriptor = [NSSortDescriptor sortDescriptorWithKey:key ascending:ascending];
return [NSArray arrayWithArray:[allKeys sortedArrayUsingDescriptors:#[dateDescriptor]]];
}
This will take all the keys from your dictionary, sort them in ascending or descending order as you desire and return that as an NSArray. This array can then be used to access the original dictionary. A sample implementation would look something like this:
for (NSString *key in [self sortedKeysFromDictionary:sampleDic ascending:NO])
{
/* get value from current key */
NSDictionary *currentDic = [sampleDic objectForKey:key];
}

Sort Descriptor not working in ios

i used the Sort Descriptor to Sort the NSMutableArray By one & multiple Values,First i tried by to sort By Price,it sort in some other Order here is my code help me,
My
i create the Dictionary by below code and added to the NSMutableArray
for(int i=0;i<[priceArray count];i++)
{
cellDict=[[NSMutableDictionary alloc]init];
[cellDict setObject:nameArray[i] forKey:#"Name"];
[cellDict setObject:splPriceArray[i] forKey:#"Percentage"];
[cellDict setObject:priceArray[i] forKey:#"Price"];
[resultArray addObject:cellDict];
}
// To Sort in Ascending Order
NSSortDescriptor *sort =[[NSSortDescriptor alloc] initWithKey:#"Price" ascending:YES];
NSArray *descriptors = [NSArray arrayWithObjects:sort, nil];
NSArray *sortedArray=[resultArray sortedArrayUsingDescriptors:descriptors];
NSLog(#"Result %# Sorted arr %#",resultArray, sortedArray);
And Output is:
Result (
{
Name = "Black Eyed Peas";
Percentage = 0;
Price = 80;
},
{
Name = "Black Gram";
Percentage = 0;
Price = 56;
},
{
Name = "Channa White";
Percentage = 0;
Price = 100;
},
{
Name = "Double Beans";
Percentage = 0;
Price = 95;
},
{
Name = "Gram Dall";
Percentage = 0;
Price = 100;
},
{
Name = "Green Moong Dal";
Percentage = 0;
Price = 150;
},
{
Name = "Ground Nut";
Percentage = 0;
Price = 140;
},
{
Name = "Moong Dal";
Percentage = 0;
Price = 75;
},
{
Name = "Orid Dal";
Percentage = 0;
Price = 100;
},
{
Name = "Toor Dal";
Percentage = 0;
Price = 150;
}
) Sorted arr (
{
Name = "Channa White";
Percentage = 0;
Price = 100;
},
{
Name = "Gram Dall";
Percentage = 0;
Price = 100;
},
{
Name = "Orid Dal";
Percentage = 0;
Price = 100;
},
{
Name = "Ground Nut";
Percentage = 0;
Price = 140;
},
{
Name = "Green Moong Dal";
Percentage = 0;
Price = 150;
},
{
Name = "Toor Dal";
Percentage = 0;
Price = 150;
},
{
Name = "Black Gram";
Percentage = 0;
Price = 56;
},
{
Name = "Moong Dal";
Percentage = 0;
Price = 75;
},
{
Name = "Black Eyed Peas";
Percentage = 0;
Price = 80;
},
{
Name = "Double Beans";
Percentage = 0;
Price = 95;
}
)
Here The Sorted Array Sorting in some other Order I want to sort this in Ascending order by price.
It's unclear what your test data looks like - but the following snippet works as expected
NSArray *priceArray = [NSArray arrayWithObjects:#(74),#(100),#(100),#(130), nil];
NSArray *nameArray = [NSArray arrayWithObjects:#"Yva",#"Hallo", #"Adam", #"Xavier", nil];
NSMutableArray *resultArray = [NSMutableArray new];
for(int i=0;i<[priceArray count];i++)
{
NSMutableDictionary *cellDict=[[NSMutableDictionary alloc]init];
[cellDict setObject:nameArray[i] forKey:#"Name"];
[cellDict setObject:priceArray[i] forKey:#"Percentage"];
[cellDict setObject:priceArray[i] forKey:#"Price"];
[resultArray addObject:cellDict];
}
// Sort by Name
//NSSortDescriptor *sort =[[NSSortDescriptor alloc] initWithKey:#"Price" ascending:YES];
// Sort by Name
NSSortDescriptor *sort =[[NSSortDescriptor alloc] initWithKey:#"Name" ascending:YES selector:#selector(localizedCaseInsensitiveCompare:)];
NSArray *descriptors = [NSArray arrayWithObjects:sort, nil];
NSArray *sortedArray=[resultArray sortedArrayUsingDescriptors:descriptors];
NSLog(#"Result %# Sorted arr %#",resultArray, sortedArray);
Result:
2015-07-11 12:54:54.358 ret[10480:162783] Result (
{
Name = Yva;
Percentage = 74;
Price = 74;
},
{
Name = Hallo;
Percentage = 100;
Price = 100;
},
{
Name = Adam;
Percentage = 100;
Price = 100;
},
{
Name = Xavier;
Percentage = 130;
Price = 130;
}
) Sorted arr (
{
Name = Adam;
Percentage = 100;
Price = 100;
},
{
Name = Hallo;
Percentage = 100;
Price = 100;
},
{
Name = Xavier;
Percentage = 130;
Price = 130;
},
{
Name = Yva;
Percentage = 74;
Price = 74;
}
)

NSPredicate for array of Dictionaries generating null array

I'm a Begginer in Objective-C coding and I need some help on NSPredicates.
I need to filter (by id_especie) an Array of Dictionaries that I've parsed from a Json file and retrieve the data to another array. Unfortunate all I got is a null array;
That's my Array of Dictionaries (id_especie mean species_id and id_raca mean breed_id) :
{
"id_especie" = 1;
"id_raca" = 1;
raca = Afghanhound;
},
{
"id_especie" = 1;
"id_raca" = 2;
raca = "Airedale Terrier";
},
{
"id_especie" = 1;
"id_raca" = 3;
raca = Akita;
},...,
{
"id_especie" = 2;
"id_raca" = 47;
raca = "N/I";
},
{
"id_especie" = 2;
"id_raca" = 48;
raca = Siames;
},
{
"id_especie" = 3;
"id_raca" = 49;
raca = Periquito;
},
{
"id_especie" = 4;
"id_raca" = 50;
raca = Cobra;
},
{
"id_especie" = 4;
"id_raca" = 51;
raca = Lagarto;
},
{
"id_especie" = 5;
"id_raca" = 52;
raca = "Furao";
},
{
"id_especie" = 5;
"id_raca" = 53;
raca = Hamster;
},
{
"id_especie" = 6;
"id_raca" = 54;
raca = Outros;
}
And this is my code:
.h
#property (nonatomic, strong) NSMutableArray *arrayBreedAndSpecies;
#property (nonatomic, strong) NSArray *filteredArray; //edited
.m
NSError *errorLoad = nil;
NSURL *jsonUrl = [[NSURL alloc]initWithString:#"http://marcosdegni.com.br/petsistema/teste/raca.php"];
NSString *jsonString = [NSString stringWithContentsOfURL:jsonUrl encoding:NSUTF8StringEncoding error:&errorLoad];
if (!errorLoad) {
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];
self.arrayBreedAndSpecies = [[NSMutableArray alloc] initWithArray:jsonArray];
}
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"%# = %#",#"id_especie", #"2"];
[self.filteredArray setArray: [self.arrayBreedAndSpecies filteredArrayUsingPredicate:predicate]];
NSLog(#"Filter: %#", self.filteredArray);
OK I've noticed a few errors with your NSPredicate code:
1) A dynamic key path in a predicate should be %K not %#.
2) To check if a number value is equal to another you need to use == not just =
Therefore the last section of code should be:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"%K == %i",#"id_especie", 2];
self.filteredArray = [NSArray arrayWithArray:[self.arrayBreedAndSpecies filteredArrayUsingPredicate:predicate]];
NSLog(#"Filter: %#", self.filteredArray);
I'm assuming here that the id_especie property is a number value. If it is a string value you could use the predicate: [NSPredicate predicateWithFormat:#"%K MATCHES[cd] %#", #"id_especie", #"2"];
Hope this helps
just a guess here, because there isn't a working code example here:
[self.filteredArray setArray: [self.arrayBreedAndSpecies filteredArrayUsingPredicate:predicate]];
if self.filteredArray is nil, that line will do nothing... I bet you really mean:
self.filteredArray = [self.arrayBreedAndSpecies filteredArrayUsingPredicate:predicate];

Why data added in to array multiple times?

I load data from json and then add it to nsmutablearray like this:
- (void)loadData
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
// Create array to hold dictionaries
myObject = [[NSMutableArray alloc] init];
NSData *jsonData = [NSData dataWithContentsOfURL:
[NSURL URLWithString:#"http://www.domain.com/json.php"]];
if(jsonData != nil)
{
NSError *error = nil;
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
if (error == nil){
dispatch_sync(dispatch_get_main_queue(), ^{
// values in foreach loop
for (NSMutableArray *tempArray in jsonObjects) {
[myObject addObject:tempArray];
NSSortDescriptor * sortDesc = [[NSSortDescriptor alloc] initWithKey:#"id.doubleValue" ascending:NO];
[myObject sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];
[self.tableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:YES];
[self performSelectorOnMainThread:#selector(endAnimating) withObject:nil waitUntilDone:YES];
}
});
}
}
});
}
if I check with NSLog "tempArray" it's looks ok, but if I check "myObject", data added to it multiple times. How to add data just one time in to my "myObject" array?
EDIT:
My JSON result:
[{"id":"7","title":"monkey","thumb":"http:\/\/icon.s.photosight.ru\/img\/8\/e09\/5045427_thumb.jpg","url":"http:\/\/icon.s.photosight.ru\/img\/8\/e09\/5045427_large.jpg","day":"perjantai","date":"0","likes":"2","device_id":"1111","active":"1"},
{"id":"11","title":"Bukashka","thumb":"http:\/\/icon.s.photosight.ru\/img\/f\/b3b\/5078973_thumb.jpg","url":"http:\/\/icon.s.photosight.ru\/img\/f\/b3b\/5078973_large.jpg","day":"perjantai","date":"0","likes":"1","device_id":"1111","active":"1"},
{"id":"12","title":"blya","thumb":"http:\/\/icon.s.photosight.ru\/img\/f\/c1d\/5076251_thumb.jpg","url":"http:\/\/icon.s.photosight.ru\/img\/f\/c1d\/5076251_large.jpg","day":"perjantai","date":"0","likes":"1","device_id":"1111","active":"1"}]
My NSLog(#"%#", myObject);
2013-06-12 18:45:52.228 testApp[960:60b] (
{
active = 1;
date = 0;
day = perjantai;
"device_id" = 1111;
id = 7;
likes = 2;
thumb = "http://icon.s.photosight.ru/img/8/e09/5045427_thumb.jpg";
title = monkey;
url = "http://icon.s.photosight.ru/img/8/e09/5045427_large.jpg";
}
)
2013-06-12 18:45:52.230 testApp[960:60b] (
{
active = 1;
date = 0;
day = perjantai;
"device_id" = 1111;
id = 11;
likes = 1;
thumb = "http://icon.s.photosight.ru/img/f/b3b/5078973_thumb.jpg";
title = Bukashka;
url = "http://icon.s.photosight.ru/img/f/b3b/5078973_large.jpg";
},
{
active = 1;
date = 0;
day = perjantai;
"device_id" = 1111;
id = 7;
likes = 2;
thumb = "http://icon.s.photosight.ru/img/8/e09/5045427_thumb.jpg";
title = monkey;
url = "http://icon.s.photosight.ru/img/8/e09/5045427_large.jpg";
}
)
2013-06-12 18:45:52.237 testApp[960:60b] (
{
active = 1;
date = 0;
day = perjantai;
"device_id" = 1111;
id = 12;
likes = 1;
thumb = "http://icon.s.photosight.ru/img/f/c1d/5076251_thumb.jpg";
title = blya;
url = "http://icon.s.photosight.ru/img/f/c1d/5076251_large.jpg";
},
{
active = 1;
date = 0;
day = perjantai;
"device_id" = 1111;
id = 11;
likes = 1;
thumb = "http://icon.s.photosight.ru/img/f/b3b/5078973_thumb.jpg";
title = Bukashka;
url = "http://icon.s.photosight.ru/img/f/b3b/5078973_large.jpg";
},
{
active = 1;
date = 0;
day = perjantai;
"device_id" = 1111;
id = 7;
likes = 2;
thumb = "http://icon.s.photosight.ru/img/8/e09/5045427_thumb.jpg";
title = monkey;
url = "http://icon.s.photosight.ru/img/8/e09/5045427_large.jpg";
}
)
WORKING SOLUTION BY: danypata
in viewDidLoad put myObject = [[NSMutableArray alloc] init];
then
- (void)loadData
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSData *jsonData = [NSData dataWithContentsOfURL:
[NSURL URLWithString:#"http://www.domain.com/json.php"]];
if(jsonData != nil)
{
NSError *error = nil;
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
if (error == nil){
[myObject removeAllObjects];
for (NSMutableDictionary *tempDict in jsonObjects) {
[myObject addObject:tempDict];
}
NSSortDescriptor * sortDesc = [[NSSortDescriptor alloc] initWithKey:#"id.doubleValue" ascending:NO];
[myObject sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];
dispatch_sync(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
[self.tableView.pullToRefreshView stopAnimating];
});
}
}
});
}
One possible cause of your problem is that the tempArray arrays contains same objects, but to reply to your question `how to add just one time in to my "myObject" array" there are two easy solutions
One, use containsObject: method like this:
if([myObject containsObject:tempArray] == NO) {
[myObject addObject:tempArray]
}
Second, which I think is more elegant use NSMutableSet (`NSMutableSet adds objects only if the object is not already added). You can use it like this:
NSMutableSet *set = [[NSMutableSet alloc] init];
[set addObject:tempArray];
//after you added all objects just do the following after you init your myObject
[myObject addObjectsFromArray:[set allObjects]]
EDIT
Your problem is caused by the for loop. You are nto extracting properly the data, in your JSON you have an array of dictionaries not an array of arrays so you should change the for loop like this:
for (NSDictionary *tempDict in jsonObjects) {
[myObject addObject:tempDict];
//other operations here
}

Resources