JSON data issue iPhone - iphone

I am getting this data from JSON web services
[{"identity":"DEMO","assets":[{"identity":"34DL3611","systemId":"544507"},{"identity":"34GF0512","systemId":"5290211"},{"identity":"34HH1734","systemId":"111463609"},{"identity":"34HH1736","systemId":"111463622"},{"identity":"34YCJ15","systemId":"294151155"}],"systemId":4921244}]
I am using this method to get the values of assets for identity ("assets":[{"identity":"34DL3611","systemId":"544507"}):
vehicleList = [dict objectForKey: #"assets"];
self.listVehicles = [[NSMutableArray alloc] init];
for (NSUInteger index = 0; index < [vehicleList count]; index++) {
itemDict = [vehicleList objectAtIndex: index];
[self.listVehicles addObject:[itemDict objectForKey:#"identity"]];
}
how can I get the systemId values ... ?
I have tried this for systemId
vehicleListID = [dict objectForKey:#"systemId"];
self.listVehiclesID =[[NSMutableArray alloc]init];
for (NSUInteger index = 0; index < [vehicleListID count]; index++) {
assetsIdDict = [vehicleListID objectAtIndex: index];
[self.listVehiclesID addObject:[assetsIdDict objectForKey:#"systemId"]];
}
but getting error: [__NSCFNumber count]: unrecognized selector sent to instance 0x784c730

You're basically almost there. You just want this probably:
NSString *systemId = [itemDict objectForKey:#"systemId"];
With regard to this code you have:
vehicleListID = [dict objectForKey:#"systemId"];
self.listVehiclesID =[[NSMutableArray alloc]init];
for (NSUInteger index = 0; index < [vehicleListID count]; index++) {
assetsIdDict = [vehicleListID objectAtIndex: index];
[self.listVehiclesID addObject:[assetsIdDict objectForKey:#"systemId"]];
}
... well that is just totally wrong. That's returning the NSNumber which in your example JSON is 4921244 right at the end of the JSON string. You're then calling count on it, but it's not an array, so it crashes.
If you want to get all the values out of that JSON you can use this:
NSNumber *outerIdentity = [dict objectForKey:#"identity"];
NSNumber *outerSystemId = [dict objectForKey:#"systemId"];
NSArray *vehicleList = [dict objectForKey:#"assets"];
for (NSUInteger index = 0; index < [vehicleList count]; index++) {
NSDictionary *itemDict = [vehicleList objectAtIndex: index];
NSString *identity = [itemDict objectForKey:#"identity"];
NSString *systemId = [itemDict objectForKey:#"systemId"];
}
Then do whatever it is you want to do with all those objects.

The json response you are getting is an array. vehicleList should be the objectatIndex 0 of json response.
NSDictionary *vehicleList = [[arrayLoadedFromJson objectAtIndex:0] objectForKey: #"assets"];
vehicleList = [dict objectForKey: #"assets"];
self.listVehicles = [[NSMutableArray alloc] init];
for (NSUInteger index = 0; index < [vehicleList count]; index++) {
itemDict = [vehicleList objectAtIndex: index];
[self.listVehicles addObject:[itemDict objectForKey:#"identity"]];
[self.listVehicles addObject:[itemDict objectForKey:#"systemId"]];
}
This you have to insert:-in your code
[self.listVehicles addObject:[itemDict objectForKey:#"systemId"]];

For that to having in separate array, you need to initialize new NSMutableArray and add the objects.
Else, the better way is, declare a new class with 2 NSString members say, identity and systemId. Extract the values from JSON and assign to the class members. And add that object to the array.

Related

NSMutableArray (addObject) not working inside if statement

i have this code :
NSMutableArray *arr = [NSMutableArray array];
for (int i = 0; i <[titleNews count]; ++i) {
TFHppleElement *someText =[titleNews objectAtIndex:i];
NSString *result = [someText content];
[arr addObject:result];
if ([[arr objectAtIndex:i]isEqualToString:#"-- : --"]) {
[arr replaceObjectAtIndex:i withObject:#"x"];
[arr addObject:#"/"];
}
NSLog(#"%#",[arr objectAtIndex:i]);
}
the (replaceObjectAtIndex: withObject:) work fine but the (addObject)method not working
You're presuming that the "result" that you add to the array will always be at index i. But the first time that you fall into your "if" body, you'll add an i+1 element ("/") and from then on everything will be off by one.

how to create an array of string or float in Objective-C

i need some help here, i need to know how to create an array of string retrieved from an array. i'm using powerplot for graph and it only accept float or string array.
i need to create something something like this dynamically.
NSString * sourceData[7] = {#"2", #"1", #"4", #"8", #"14", #"15", #"10"};
Below are my code to find out the numbers in strings.
NSInteger drunked = [appDelegate.drinksOnDayArray count];
NSMutableArray * dayArray = [[NSMutableArray alloc] init];
NSMutableArray * sdArray = [[NSMutableArray alloc] init];
//float *sdArray[7];
for (int i=0; i<drunked; i++) {
DayOfDrinks *drinksOnDay = [appDelegate.drinksOnDayArray objectAtIndex:i];
NSString * dayString= [NSDate stringForDisplayFromDateForChart:drinksOnDay.dateConsumed];
[dayArray addObject:dayString];
NSLog(#"%#",[dayArray objectAtIndex:i]);
drinksOnDay.isDetailViewHydrated = NO;
[drinksOnDay hydrateDetailViewData];
NSString * sdString= [NSString stringWithFormat:#"%#", drinksOnDay.standardDrinks];
[sdArray addObject:sdString];
NSString *tempstring;
NSLog(#"%#",[sdArray objectAtIndex:i]);
}
thanks for the help :)
Array's in Objectice-C aren't that hard to work with:
NSMutableArray *myArray = [NSMutableArray array];
[myArray addObject:#"first string"]; // same with float values
[myArray addObject:#"second string"];
[myArray addObject:#"third string"];
int i;
int count;
for (i = 0, count = [myArray count]; i < count; i = i + 1)
{
NSString *element = [myArray objectAtIndex:i];
NSLog(#"The element at index %d in the array is: %#", i, element); // just replace the %# by %d
}
You can either use NSArray or NSMutableArray - depending on your needs, they offer different functionality.
Following tutorial covers exactly what you are looking after:
http://www.cocoalab.com/?q=node/19
You can also add the elements to the array when you init (and optionally add them later only if you are using the Mutable version of a collection class:
NSMutableArray *myArray = [[NSMutableArray alloc] initWithObjects:#"2", #"1", #"4", #"8", #"14", #"15", #"10", nil];
[myArray addObject:#"22"];
[myArray addObject:#"50"];
//do something
[myArray release];
You can use malloc to create a C-style array. something like this should work:
NSString **array = malloc(numElements * sizeof(NSString *))
some code here
free(array)
Be aware that unlike NSMutable array, c arrays won't do a retain, so you have to manage it if needed. And don't forget the free

how to create an C Array

his guys,
i think this is a simple question but i do not know how to do it.
how do i create the line below dynamically from an array?
this is what i need to call.
//data source
NSString * sourceData[7] = {#"2", #"1", #"4", #"8", #"14", #"15", #"10"};
chartData = [WSData dataWithValues:[WSData arrayWithString:sourceData withLen:7]];
+ (NSArray *)arrayWithString:(NSString *[])strings
withLen:(NSUInteger)len {
NSMutableArray *tmpArr = [NSMutableArray
arrayWithCapacity:len];
NSUInteger i;
for (i=0; i<len; i++) {
[tmpArr addObject:strings[i]];
}
return [NSArray arrayWithArray:tmpArr];
}
thanks for all the help especially Daniel :)
this is the answer to the question
NSMutableArray * dayArray = [[NSMutableArray alloc] init];
dayArray = [NSMutableArray arrayWithCapacity:7];
NSMutableArray * sdArray = [[NSMutableArray alloc] init];
sdArray = [NSMutableArray arrayWithCapacity:7];
NSInteger drunked = [appDelegate.drinksOnDayArray count];
if (drunked !=0)
{
for(int i=6; i>=0; i--)
{
DayOfDrinks *drinksOnDay = [appDelegate.drinksOnDayArray objectAtIndex:i];
NSString * dayString= [NSDate stringForDisplayFromDateForChart:drinksOnDay.dateConsumed];
[dayArray addObject:dayString];//X label for graph the day of drink.
drinksOnDay.isDetailViewHydrated = NO;
[drinksOnDay hydrateDetailViewData];
NSNumber *sdNumber = drinksOnDay.standardDrinks;
[sdArray addObject: sdNumber];
}
NSString *sData[7];// = malloc(7 * sizeof(NSString *));
for (int i=0; i<7; i++)
{
DayOfDrinks *drinksOnDay = [appDelegate.drinksOnDayArray objectAtIndex:i];
sData[i] = [NSString stringWithFormat:#"%#",drinksOnDay.standardDrinks];
}
NSString * sourceData[7] = {sData[6],sData[5],sData[4],sData[3],sData[2],sData[1],sData[0] };
}
If you are only using the array as a call parm, and are not storing it somewhere or returning it from your current method:
NSString* sourceData[7];
for (i = 0; i < 7; i++) {
int num = <getTheValueYouWant>;
sourceData[i] = [NSString stringWithFormat:#"%d", num];
}
But note that if you intend to return the array, or store it in some long-lived variable, you need an entirely different setup.
So this is how you would create an NSMutableArray. Mutable because you're creating it at runtime.
NSString * sourceData = [[NSString alloc] initWithFormat:#""];
//assuming the array you have is arr with NSNumber objects
for (NSNumber *num in arr) {
[sourceData stringByAppendingFormat:#"%#", num];
}
You can try below code with the loop as you required.....
NSMutableArray *array;
array = [[NSMutableArray alloc] init];
[array addObject:[NSNumber numberWithFloat:1.0f]];
[array release];

NSArray objects go out of scope after returning pointer

I am attempting to use the below code in a function to return an array of dictionary objects. Unfortunately, after the return to the next function in the stack all of the rows in the mutable array have become 'out of scope'. From my understanding, the array should retain the row (dictionary) object automatically so even after the return, where the row pointer goes out of scope, the row objects should still have a retain count of 1. What am I doing wrong here? How do I build this array in such a way that the objects it contains don't get released?
for (int i = 1; i < nRows; i++)
{
NSMutableDictionary* row = [[[NSMutableDictionary alloc] initWithCapacity:nColumns] ];
for(int j = 0; j < nColumns; j++)
{
NSString* key = [[NSString stringWithUTF8String:azResult[j]] ];
NSString* value = [[NSString stringWithUTF8String:azResult[(i*nColumns)+j]] ];
[row setValue:value forKey:key];
}
[dataTable addObject:row];
}
return dataTable;
This line:
NSMutableDictionary* row = [[NSMutableDictionary alloc] initWithCapacity:nColumns] ];
should use the autorelease:
NSMutableDictionary* row = [[[NSMutableDictionary alloc] initWithCapacity:nColumns] ] autorelease];
From what i understand:
-(NSMutableArray*) getArrayOfDictionaries{
int nRows=somenumber;
int nColumns=someOthernumber;
char **azResult=someArrayOfStrings;
NSMutableArray *dataTable=[[NSMutableArray alloc] init];
for (int i = 1; i < nRows; i++)
{
NSMutableDictionary* row = [[[NSMutableDictionary alloc] initWithCapacity:nColumns]];
for(int j = 0; j < nColumns; j++)
{
NSString* key = [[NSString stringWithUTF8String:azResult[j]] ];
NSString* value = [[NSString stringWithUTF8String:azResult[(i*nColumns)+j]] ];
[row setValue:value forKey:key];
}
[dataTable addObject:row];
//you should add the following line to avoid leaking
[row release];
}
//watch for leaks
return [dataTable autorelease];
//beyond this point dataTable will be out of scope
}
-(void) callingMethod {
//dataTable is out of scope here, you should look into arrayOfDictionaries variable
NSMutableArray* arrayOfDictionaries=[self getArrayOfDictionaries];
}
You should look into the local variable in callingMethod instead of dataTable which is local to the method I called getArrayOfDictionaries

Find indices of duplicates in a NSArray

i have an array like
[chapter,indent,left,indent,nonindent,chapter,chapter,indent,indent,left];
i need to find indexes of duplicates and also non duplicate elements .
how to do this...........give some sample code or logic......
thanks in advance
iam using objective c.....
NSArray *myWords = [string componentsSeparatedByString:#"class=\""];
int count_var=[myWords count];
tmp1=#"";
for(int i=1;i<count_var;i++)
{
str=[NSString stringWithFormat:#"\n%#",[myWords objectAtIndex:i]];
class=[str componentsSeparatedByString:#"\""];
NSString *tmp=[NSString stringWithFormat:#"%#",[class objectAtIndex:0]];
tmp1=[[NSString stringWithFormat:#"%#",tmp1] stringByAppendingString:[NSString stringWithFormat:#"%#",tmp]];
}
t1.editable=NO;
t1.text=tmp1;
NSArray *tempo=[[NSArray alloc]init];
tempo=[tmp1 componentsSeparatedByString:#"\n"];
tempCount=[tempo count];
this is my sample code...in this the array tempo contains all objects from that array i want to get index of duplicate strings≥.
You could build a dictionary mapping the objects to index sets. For every index set, a -count of 1 means no duplicates, > 1 means there are duplicates.
NSArray *arr = [NSArray arrayWithObjects:...];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSUInteger i=0; i<[arr count]; ++i) {
id obj = [arr objectAtIndex:i];
NSMutableIndexSet *ids = [dict objectForKey:obj];
if (!ids) {
ids = [NSMutableIndexSet indexSet];
[dict setObject:ids forKey:obj];
}
[ids addIndex:i];
}
NSLog(#"%#", dict);