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
}
Related
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.
in my project i applied the following code
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6);
diagnosisdict = [[[dict6 objectForKey:#"diagnoses"] objectAtIndex:0] objectForKey:#"DiagnosesHospitals"];
diagnosedictforname = [[[dict6 objectForKey:#"diagnoses"]objectAtIndex:0]objectForKey:#"Diagnoses"];
NSLog(#" for ref id =%# ,name of diagnose=%# data is= %#",refidstr,diagnosedictforname ,diagnosisdict);
and the output in console is comes out as in the form
str : {
diagnoses = (
{
Diagnoses = {
"diagnosis_name" = "TRANSIENT ISCHEMIA";
};
DiagnosesHospitals = {
"charge_amt" = "1300.00";
discharges = "11200.00";
"hospital_id" = 3341;
id = 163080;
"medicare_amt" = "100.00";
"total_amt" = "1100.00";
};
}
);
response = 200;
}
ref id =3341 ,name of diagnose={
"diagnosis_name" = "TRANSIENT ISCHEMIA";
} data is= {
"charge_amt" = "1300.00";
discharges = "11200.00";
"hospital_id" = 3341;
id = 163080;
"medicare_amt" = "100.00";
"total_amt" = "1100.00";
}
now i just want to embed the values of both the Dictionaries into one dictionary
someone please help me to sort out this issue.
Make a mutable copy of the first dictionary:
NSMutableDictionary * mutDic = [dic1 mutableCopy];
and then:
[mutDic addEntriesFromDictionary:dic2];
Try this code:
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6);
NSMutableDictionary *diagnosisdict = [[[dict6 objectForKey:#"diagnoses"] objectAtIndex:0] objectForKey:#"DiagnosesHospitals"];
NSDictionary *diagnosedictforname = [[[dict6 objectForKey:#"diagnoses"]objectAtIndex:0]objectForKey:#"Diagnoses"];
NSArray *keys = [diagnosedictforname allKeys];
for (int i =0; i < keys.count; i++) {
NSString *key = [keys objectAtIndex:i];
[diagnosisdict setValue:[diagnosedictforname valueForKey:key] forKey:key];
}
NSLog(#"your dic -> %#", diagnosisdict);
I need to convert an NSMutableArray to an NSArray from JSON. I loaded the JSON and put it in an NSMutableArray.
NSMutableArray *banner = [[NSMutableArray alloc] init];
banner = [responseObject objectForKey:#"banner"];
This is test for loop:
for(int i = 0; i < [slider count]; i++) {
NSLog(#"%#", [[banner objectAtIndex:i] objectForKey:#"resim"]); }
This is log from the JSON:
(
{
id = 1;
resim = "http://localhost/sample_Files/banner_api/1.jpg";
},
{
id = 2;
resim = "http://localhost/sample_Files/banner_api/2.jpg";
},
{
id = 3;
resim = "http://localhost/sample_Files/banner_api/3.jpg";
}
)
I want to set all of this to be like the below NSArray:
NSArray *allImages = #[#"http://localhost/sample_Files/banner_api/1.jpg",#"http://localhost/sample_Files/banner_api/2.jpg",#"http://localhost/sample_Files/banner_api/3.jpg"];
How can I do this?
NSMutableArray * muArr = [NSMutableArray new];
for(NSDictionary * dict in yourMuArr) {
[muArr addObject:dict[#"resim"]];
}
NSArray * allImages = [NSArray arrayWithArray:muArr];
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.
I have the following code and it is working to an extent :
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSString *strURL = [NSString stringWithFormat:#"http://localhost:8888/service.php"];
NSURL *url = [NSURL URLWithString:strURL];
NSData * data = [NSData dataWithContentsOfURL:url];
NSError * error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
AdObject *someAdObject = [[AdObject alloc] init];
//NSLog(#"%#", json);
self.detailLabel.text = self.tempString;
}
Now when the commented out NSLog actually prints the JSON dictionary, I get :
{
brand = "";
category = Games;
country = "Japan";
"discount_rate" = 50;
duration = 5;
id = 1;
"issue_date" = "2014-04-07";
location = "Heishi Mall";
title = "Gamestory videogames sales!";
user = "";
}
)
I created an Ad object which has properties such as title, location, country, etc (as reflected above). I would like to access the JSON above and store value in object variables.
You can access that values :-
for(NSDictionary *item in json) {
NSLog(#"%#",[item valueForKey:#"key"]);
someAdObject.key = [item valueForKey:#"key"];
}
Try this and review your json also
AdObject *someAdObject = nil;
for(NSDictionary *item in json) {
someAdObject = [[AdObject alloc] init];
someAdObject.category = [item valueForKey#"category"];
someAdObject.country = [item valueForKey#"country"];
someAdObject.discount_rate = [item valueForKey#"discount_rate"];
someAdObject.duration = [item valueForKey#"duration"];
//and same all of your required object properties
}