NSLog give me this when i print some NSDictionary object. I see, that in this NSDictionary are few NSDictionary objects. i must to send this to UITextView, but this must be one list without {ExifAux}, {Exif}, {IPTC}, {TIFF}. how can i do this?
2012-01-21 13:33:23.818 foto-edytor[7838:17903] {
ColorModel = RGB;
DPIHeight = 240;
DPIWidth = 240;
Depth = 8;
PixelHeight = 900;
PixelWidth = 598;
"{ExifAux}" = {
ImageNumber = 5280;
LensID = 159;
LensInfo = (
35,
35,
"1.8",
"1.8"
);
LensModel = "35.0 mm f/1.8";
SerialNumber = 6055523;
};
"{Exif}" = {
ApertureValue = "3.356144";
BodySerialNumber = 6055523;
ColorSpace = 1;
ComponentsConfiguration = (
1,
2,
3,
0
);
Contrast = 0;
CustomRendered = 0;
DateTimeDigitized = "2011:11:12 11:54:18";
DateTimeOriginal = "2011:11:12 11:54:18";
DigitalZoomRatio = 1;
ExifVersion = (
2,
2,
1
);
ExposureBiasValue = "-1.333333";
ExposureMode = 0;
ExposureProgram = 3;
ExposureTime = "0.01666667";
FNumber = "3.2";
FileSource = 3;
Flash = 0;
FlashPixVersion = (
1,
0
);
FocalLenIn35mmFilm = 52;
FocalLength = 35;
GainControl = 1;
ISOSpeedRatings = (
400
);
LensModel = "35.0 mm f/1.8";
LensSpecification = (
35,
35,
"1.8",
"1.8"
);
LightSource = 0;
MaxApertureValue = "1.6";
MeteringMode = 2;
PixelXDimension = 1442971648;
PixelYDimension = "-2080178176";
Saturation = 0;
SceneCaptureType = 0;
SceneType = 1;
SensingMethod = 2;
Sharpness = 0;
ShutterSpeedValue = "5.906891";
SubjectDistRange = 0;
SubjectDistance = "1.41";
SubsecTimeDigitized = 25;
SubsecTimeOriginal = 25;
UserComment = SZULC;
WhiteBalance = 0;
};
"{IPTC}" = {
Byline = "SZULC TOMASZ";
CopyrightNotice = "SZULC TOMASZ";
};
"{TIFF}" = {
Artist = "SZULC TOMASZ";
Copyright = "SZULC TOMASZ";
DateTime = "2012:01:20 17:50:58";
Make = "NIKON CORPORATION";
Model = "NIKON D300S";
ResolutionUnit = 2;
Software = "Ver.1.01";
XResolution = 240;
YResolution = 240;
"_YCbCrPositioning" = 1;
};
}
It's not the most beautiful way, but I guess this should work:
- (NSString *)stringOutputForDictionary:(NSDictionary *)inputDict {
NSMutableString * outputString = [NSMutableString stringWithCapacity:256];
NSArray * allKeys = [inputDict allKeys];
for (NSString * key in allKeys) {
if ([[inputDict objectForKey:key] isKindOfClass:[NSDictionary class]]) {
[outputString appendString: [self stringOutputForDictionary: (NSDictionary *)inputDict]];
}
else {
[outputString appendString: key];
[outputString appendString: #": "];
[outputString appendString: [[inputDict objectForKey: key] description]];
}
[outputString appendString: #"\n"];
}
return [NSString stringWithString: outputString];
}
Related
I have a large dictionary (partial example below - there are 26 products in total) that I need to send back to a ColdFusion web service. I was able to make a connection to the web service and when checking the NSHTTPURLResponse statusCode I get 200, which indicates the service is receiving and returning something (right?) but when I check the return I get HTML results, part of which states an error:
coldfusion.runtime.MissingArgumentException: The PAJSONSTRING parameter to the setPurchaseAgreements function is required but was not passed in.
which to me seems that I am not setting the value for the variable PAJSONSTRING. So my question is how would I be able to pass this JSON to that variable? I thought of the query string but when that would end up passing somewhere between 5000 and 7000 characters depending on what the user is sending back. But I can't seem to find an example of how to set a parameter value using POST. Any thoughts would be appreciated.
PA = {
"CUSTOMER_ID" = xxxxxxx;
"GROSS_GROWTH_NO_YF_FLU" = 39385;
"GROSS_GROWTH_ONLINE_DISC" = 394;
"GROSS_GROWTH_SALES" = 56500;
"GROSS_PROJECTED_NO_YF_FLU" = 35805;
"GROSS_PROJECTED_ONLINE_DISC" = 358;
"GROSS_PROJECTED_SALES" = 52920;
"GROSS_SALES" = 0;
"GROSS_SALES_CUST_PRICE_LIST" = 0;
"GROWTH_MATCH_REBATE_AMT" = 3509;
"GROWTH_NET_SALES" = 56500;
"GROWTH_NET_SALES_NO_YF_FLU" = 394;
"GROWTH_PROJ_SALES_NO_YF_FLU" = 3509;
"GROWTH_REBATE_AMT" = 3509;
"GROWTH_REBATE_PCT" = 9;
"MATCH_GRTH_REBATE_GRTH_SALES" = "";
"MATCH_NET_SALES" = 49200;
"MATCH_PROJ_SALES_NO_YF_FLU" = 35447;
"MATCH_REBATE_AMT" = 3190;
"MATCH_REBATE_NET_DISCOUNT_SLS" = "";
"MTH_GRTH_RBT_GRTH_NET_DISC_SLS" = "";
"NEW_PRICE_DISC_NET_DISC" = "";
"ONLINE_DISCOUNT_PCT" = 1;
"OPER_ID" = xxxxxx;
"PA_CREATE_DT" = "2014-01-03 05:00:00 +0000";
"PA_ID" = 0;
"PA_NAME" = "Copy of 8";
"PA_STATUS_ID" = 2;
"PRICELIST_TYPE_ID" = 5;
"PRICE_LIST_GROWTH_SALES" = "";
"PRICE_LIST_PROJECTED_SALES" = "";
"REBATE_ELG_PROD_COUNT" = 0;
"SALES_ROSTER_ID" = 20016;
"START_DT" = "2014-01-03 17:56:12 +0000";
"STATUS_PRICE_LIST_NET_DISC_SLS" = "";
"STATUS_PRICE_LIST_PROJ_SALES" = "";
"TOTAL_GRTH_MATCH_REBATE_AMT" = "";
"UPFRONT_DISCOUNT_PCT" = 0;
};
PRODUCTS = (
{
"DISCOUNT_DOSE_PRICE" = 8;
"DISCOUNT_UNIT_PRICE" = 80;
"GROWTH_DOSES" = 0;
"GROWTH_PROJECTED" = 0;
"LIST_DOSE_PRICE" = 0;
"OPER_ID" = 20016;
"PA_PRODUCT_ID" = xxxxx;
"PRODUCT_ID" = xxxxxx;
"SALES_PROJECTED" = 0;
"SUGGESTED_DOSES" = 0;
"USER_SELECTED_DOSES" = 0;
},
{
"DISCOUNT_DOSE_PRICE" = 8;
"DISCOUNT_UNIT_PRICE" = 80;
"GROWTH_DOSES" = 0;
"GROWTH_PROJECTED" = 0;
"LIST_DOSE_PRICE" = 0;
"OPER_ID" = 20016;
"PA_PRODUCT_ID" = xxxxx;
"PRODUCT_ID" = xxxxx;
"SALES_PROJECTED" = 0;
"SUGGESTED_DOSES" = 0;
"USER_SELECTED_DOSES" = 0;
"DISCOUNT_DOSE_PRICE" = 8;
"DISCOUNT_UNIT_PRICE" = 80;
"GROWTH_DOSES" = 0;
"GROWTH_PROJECTED" = 0;
"LIST_DOSE_PRICE" = 0;
"OPER_ID" = 20016;
"PA_PRODUCT_ID" = xxxxx;
"PRODUCT_ID" = xxxxx;
"SALES_PROJECTED" = 0;
"SUGGESTED_DOSES" = 0;
"USER_SELECTED_DOSES" = 0;
"DISCOUNT_DOSE_PRICE" = 8;
"DISCOUNT_UNIT_PRICE" = 80;
"GROWTH_DOSES" = 0;
"GROWTH_PROJECTED" = 0;
"LIST_DOSE_PRICE" = 0;
"OPER_ID" = 20016;
"PA_PRODUCT_ID" = xxxxx;
"PRODUCT_ID" = xxxxx;
"SALES_PROJECTED" = 0;
"SUGGESTED_DOSES" = 0;
"USER_SELECTED_DOSES" = 0;
"DISCOUNT_DOSE_PRICE" = 8;
"DISCOUNT_UNIT_PRICE" = 80;
"GROWTH_DOSES" = 0;
"GROWTH_PROJECTED" = 0;
"LIST_DOSE_PRICE" = 0;
"OPER_ID" = 20016;
"PA_PRODUCT_ID" = xxxxx;
"PRODUCT_ID" = xxxxx;
"SALES_PROJECTED" = 0;
"SUGGESTED_DOSES" = 0;
"USER_SELECTED_DOSES" = 0;
"DISCOUNT_DOSE_PRICE" = 8;
"DISCOUNT_UNIT_PRICE" = 80;
"GROWTH_DOSES" = 0;
"GROWTH_PROJECTED" = 0;
"LIST_DOSE_PRICE" = 0;
"OPER_ID" = 20016;
"PA_PRODUCT_ID" = xxxxx;
"PRODUCT_ID" = xxxxx;
"SALES_PROJECTED" = 0;
"SUGGESTED_DOSES" = 0;
"USER_SELECTED_DOSES" = 0;
"DISCOUNT_DOSE_PRICE" = 8;
"DISCOUNT_UNIT_PRICE" = 80;
"GROWTH_DOSES" = 0;
"GROWTH_PROJECTED" = 0;
"LIST_DOSE_PRICE" = 0;
"OPER_ID" = 20016;
"PA_PRODUCT_ID" = xxxxx;
"PRODUCT_ID" = xxxxx;
"SALES_PROJECTED" = 0;
"SUGGESTED_DOSES" = 0;
"USER_SELECTED_DOSES" = 0;
"DISCOUNT_DOSE_PRICE" = 8;
"DISCOUNT_UNIT_PRICE" = 80;
"GROWTH_DOSES" = 0;
"GROWTH_PROJECTED" = 0;
"LIST_DOSE_PRICE" = 0;
"OPER_ID" = 20016;
"PA_PRODUCT_ID" = xxxxx;
"PRODUCT_ID" = xxxxx;
"SALES_PROJECTED" = 0;
"SUGGESTED_DOSES" = 0;
"USER_SELECTED_DOSES" = 0;
"DISCOUNT_DOSE_PRICE" = 8;
"DISCOUNT_UNIT_PRICE" = 80;
"GROWTH_DOSES" = 0;
"GROWTH_PROJECTED" = 0;
"LIST_DOSE_PRICE" = 0;
"OPER_ID" = 20016;
"PA_PRODUCT_ID" = xxxxx;
"PRODUCT_ID" = xxxxx;
"SALES_PROJECTED" = 0;
"SUGGESTED_DOSES" = 0;
"USER_SELECTED_DOSES" = 0;
"DISCOUNT_DOSE_PRICE" = 8;
"DISCOUNT_UNIT_PRICE" = 80;
"GROWTH_DOSES" = 0;
"GROWTH_PROJECTED" = 0;
"LIST_DOSE_PRICE" = 0;
"OPER_ID" = 20016;
"PA_PRODUCT_ID" = xxxxx;
"PRODUCT_ID" = xxxxx;
"SALES_PROJECTED" = 0;
"SUGGESTED_DOSES" = 0;
"USER_SELECTED_DOSES" = 0;
"DISCOUNT_DOSE_PRICE" = 8;
"DISCOUNT_UNIT_PRICE" = 80;
"GROWTH_DOSES" = 0;
"GROWTH_PROJECTED" = 0;
"LIST_DOSE_PRICE" = 0;
"OPER_ID" = 20016;
"PA_PRODUCT_ID" = xxxxx;
"PRODUCT_ID" = xxxxx;
"SALES_PROJECTED" = 0;
"SUGGESTED_DOSES" = 0;
"USER_SELECTED_DOSES" = 0;
"DISCOUNT_DOSE_PRICE" = 8;
"DISCOUNT_UNIT_PRICE" = 80;
"GROWTH_DOSES" = 0;
"GROWTH_PROJECTED" = 0;
"LIST_DOSE_PRICE" = 0;
"OPER_ID" = 20016;
"PA_PRODUCT_ID" = xxxxx;
"PRODUCT_ID" = xxxxx;
"SALES_PROJECTED" = 0;
"SUGGESTED_DOSES" = 0;
"USER_SELECTED_DOSES" = 0;
}
);
}
partial code...
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dictJSONData options:NSJSONWritingPrettyPrinted error:&error];
NSString* urlString = SERVICE_SET_PA;
NSURL* url = [NSURL URLWithString:urlString];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
NSOperationQueue* queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse* response, NSData* data, NSError* responseError) {
id results = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves | NSJSONReadingAllowFragments error:nil];
NSString* strResults = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
DDLogVerbose(#"%#", strResults);
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*) response;
if (data.length > 0 && responseError == nil) {
DDLogVerbose(#"%#", httpResponse.allHeaderFields);
[self receivedData:data];
} else if (data.length == 0 && error == nil) {
[self emptyReply];
} else if (responseError != nil) {
[self displayError: error];
}
}];
Edit: Logging jsonData shows this (partial post):
<7b0a2020 22504122 203a207b 0a202020 20225041 5f494422 203a2030 2c0a2020 2020224d 41544348 5f475254 485f5245 42415445 5f475254 485f5341 4c455322 203a2022 222c0a20 20202022 50415f53 54415455 535f4944 22203a20 322c0a20 20202022 47524f57 54485f50 524f4a5f 53414c45 535f4e4f 5f59465f 464c5522 203a2033 3530392c...
Deserializing it and logging it show this (partial post):
PA = {
"CUSTOMER_ID" = 955728;
"GROSS_GROWTH_NO_YF_FLU" = 39385;
"GROSS_GROWTH_ONLINE_DISC" = 394;
"GROSS_GROWTH_SALES" = 56500;
"GROSS_PROJECTED_NO_YF_FLU" = 35805;
"GROSS_PROJECTED_ONLINE_DISC" = 358;
"GROSS_PROJECTED_SALES" = 52920;
"GROSS_SALES" = 0;
"GROSS_SALES_CUST_PRICE_LIST" = 0;
"GROWTH_MATCH_REBATE_AMT" = 3509;
"GROWTH_NET_SALES" = 56500;
"GROWTH_NET_SALES_NO_YF_FLU" = 394;
"GROWTH_PROJ_SALES_NO_YF_FLU" = 3509;
...
so at least to this extent it looks fine.
I recommend using the AFNetworking Framework (osx&ios).
(https://github.com/AFNetworking/AFNetworking)
Example (from documentation)
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"foo": #"bar"};
[manager POST:#"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
I have a problem with counting my module. I am doing the following.
- (void)makeGrid:withData:(NSDictionary * )data
{
NSLog(#"aantal is: %d",[data count]);
int xStart = 0;
int yStart = 0;
int xCurrent = xStart;
int yCurrent = yStart;
int xStepSize = 165;
int yStepSize = 251;
int xCnt = 3 ;
int yCnt = [data count] % 3;
int cellCounter = 0;
UIView * gridContainerView = [[UIView alloc] init];
[keeperView addSubview:gridContainerView];
for (int y = 0; y < yCnt; y++) {
for (int x = 0; x < xCnt; x++) {
printf("xCurrent %d yCurrent %d \n", xCurrent, yCurrent);
NSString *url1 = #"player_imgUrl";
NSString *url2 = [NSString stringWithFormat:#"%i", x];
NSString *url3 = [url1 stringByAppendingString:url2];
NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:[data objectForKey:url3]]];
UIImage* myImage = [[UIImage alloc] initWithData:imageData];
UIImageView * myView = [[UIImageView alloc] initWithImage:myImage];
CGRect rect = myView.frame;
rect.origin.x = xCurrent;
rect.origin.y = yCurrent;
myView.frame = rect;
myView.tag = cellCounter;
[gridContainerView addSubview:myView];
//just label stuff
UILabel * myLabel = [[UILabel alloc] init];
[gridContainerView addSubview:myLabel];
//--------------------------------
xCurrent += xStepSize;
cellCounter++;
}
xCurrent = xStart;
yCurrent += yStepSize;
}
CGRect repositionRect = gridContainerView.frame;
repositionRect.origin.y = 100;
gridContainerView.frame = repositionRect;
}
My NSLog says that in my data object are 16 values. And when I run it, it only shows 3 imageviews. Does anybody know what I am doing wrong?
Please help,
Kind regads.
After reading your code, the number of imageviews should be (xCnt * yCnt).
Your problem is here:
int yCnt = [data count] % 3;
the yCnt is 1 when your data is 16, that's why your result is 3 imageviews only.
to overcome this issue, you should do the following:
yCnt = (data.count / xCnt) + 1;
for (int y = 0 ; y < yCnt; y++)
{
for (int x = 0; x < xCnt; x++)
{
if ((y == (yCnt - 1)) && (x > (data.count % xCnt)))
{
break;
}
else {
// Your Grid code here
}
}
}
Hope This helps.
int yCnt = [data count] % 3;
gives 1 when [data count] == 16;
i am desperately trying to find a way on how to get an Array of all the Coordinates (or a Polyline) from the google API so that I can draw my route on the MKMapView.
( By the way, I donĀ“t want to use the RegexKitLite)
As I found elsewhere, this should be the right way to call for the API.
NSString* apiUrlStr = [NSString stringWithFormat:#"http://maps.google.com/maps?output=dragdir&saddr=%#&daddr=%#", saddr, daddr];
NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
encodedString = ..... ???? // here i need some code before i can call the following Method
[self polylineWithEncodedString:encodedString];
and here is a method i found, to get a polyline.
+ (MKPolyline *)polylineWithEncodedString:(NSString *)encodedString {
const char *bytes = [encodedString UTF8String];
NSUInteger length = [encodedString lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
NSUInteger idx = 0;
NSUInteger count = length / 4;
CLLocationCoordinate2D *coords = calloc(count, sizeof(CLLocationCoordinate2D));
NSUInteger coordIdx = 0;
float latitude = 0;
float longitude = 0;
while (idx < length) {
char byte = 0;
int res = 0;
char shift = 0;
do {
byte = bytes[idx++] - 63;
res |= (byte & 0x1F) << shift;
shift += 5;
} while (byte >= 0x20);
float deltaLat = ((res & 1) ? ~(res >> 1) : (res >> 1));
latitude += deltaLat;
shift = 0;
res = 0;
do {
byte = bytes[idx++] - 0x3F;
res |= (byte & 0x1F) << shift;
shift += 5;
} while (byte >= 0x20);
float deltaLon = ((res & 1) ? ~(res >> 1) : (res >> 1));
longitude += deltaLon;
float finalLat = latitude * 1E-5;
float finalLon = longitude * 1E-5;
CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(finalLat, finalLon);
coords[coordIdx++] = coord;
if (coordIdx == count) {
NSUInteger newCount = count + 10;
coords = realloc(coords, newCount * sizeof(CLLocationCoordinate2D));
count = newCount;
}
}
MKPolyline *polyline = [MKPolyline polylineWithCoordinates:coords count:coordIdx];
free(coords);
return polyline;
}
Code from here works perfectly well:
https://gist.github.com/Muximize/3770235
+ (MKPolyline *)polylineWithGMEncodedString:(NSString *)encodedString {
const char *bytes = [encodedString UTF8String];
NSUInteger length = [encodedString lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
NSUInteger idx = 0;
NSUInteger count = length / 4;
CLLocationCoordinate2D *coords = calloc(count, sizeof(CLLocationCoordinate2D));
NSUInteger coordIdx = 0;
float latitude = 0;
float longitude = 0;
while (idx < length) {
char byte = 0;
int res = 0;
char shift = 0;
do {
byte = bytes[idx++] - 63;
res |= (byte & 0x1F) << shift;
shift += 5;
} while (byte >= 0x20);
float deltaLat = ((res & 1) ? ~(res >> 1) : (res >> 1));
latitude += deltaLat;
shift = 0;
res = 0;
do {
byte = bytes[idx++] - 0x3F;
res |= (byte & 0x1F) << shift;
shift += 5;
} while (byte >= 0x20);
float deltaLon = ((res & 1) ? ~(res >> 1) : (res >> 1));
longitude += deltaLon;
float finalLat = latitude * 1E-5;
float finalLon = longitude * 1E-5;
CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(finalLat, finalLon);
coords[coordIdx++] = coord;
if (coordIdx == count) {
NSUInteger newCount = count + 10;
coords = realloc(coords, newCount * sizeof(CLLocationCoordinate2D));
count = newCount;
}
}
MKPolyline *polyline = [MKPolyline polylineWithCoordinates:coords count:coordIdx];
free(coords);
return polyline;
}
Calling...
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%#,%#&destination=%f,%f&mode=driving&sensor=false",smAppDelegate.currPosition.latitude, smAppDelegate.currPosition.longitude, ((LocationItem*)selectedAnno).coordinate.latitude, ((LocationItem*)selectedAnno).coordinate.longitude]]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
Response...
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[self.responseDirectionData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.responseDirectionData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
[connection release];
self.responseDirectionData =nil;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(#"connection established");
[connection release];
NSError *error = nil;
NSString *responseString=[[NSString alloc]initWithData:responseDirectionData encoding:NSUTF8StringEncoding];
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
NSDictionary *jsonObjects = [jsonParser objectWithString:responseString error:&error];
NSLog(#"responce = %#",jsonObjects);
NSMutableArray *ad = [jsonObjects objectForKey:#"routes"];
NSMutableArray *data2 = [[ad objectAtIndex:0] objectForKey:#"legs"];
NSMutableArray *data3 = [[data2 objectAtIndex:0] objectForKey:#"steps"];
NSLog(#"Data3 %#", data3);
NSMutableArray *polyLinesArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [data3 count]; i++)
{
NSString* encodedPoints = [[[data3 objectAtIndex:i] objectForKey:#"polyline"] valueForKey:#"points"];
MKPolyline *route = [self polylineWithEncodedString:encodedPoints];
[polyLinesArray addObject:route];
}
[self.mapView addOverlays:polyLinesArray];
[polyLinesArray release];
}
I have a problem when trying to retrieve values from an array.
I want to get all the values from this array in order to display them in a IUTableView.
Should I use a double for function ?
{
1 = {
dishId = 1;
dishName = "Tomato Salades";
dishPrice = 13;
dishTypeId = 1;
dishTypeName = Starter;
};
2 = {
dishId = 2;
dishName = "Leeks Salades";
dishPrice = 12;
dishTypeId = 1;
dishTypeName = Starter;
};
3 = {
dishId = 3;
dishName = Fries;
dishPrice = 14;
dishTypeId = 2;
dishTypeName = "Main Course";
};
4 = {
dishId = 4;
dishName = Beef;
dishPrice = 15;
dishTypeId = 2;
dishTypeName = "Main Course";
};
7 = {
dishId = 7;
dishName = "Cheese Cake";
dishPrice = 8;
dishTypeId = 3;
dishTypeName = Dessert;
};
menuCountry = France;
menuDescription = "un menu pas comme les autres pour une region pas comme les autres";
menuId = 1;
menuName = "Autour de l\\Alsace";
menuState = 1;
}
This is my Python code which creates a Dictionary in a Array :
def getDishOfTheWeek():
menuArray = []
menuDic = Ddict(dict)
for menu in Menus.select().where(state=True):
menuDic['menuId']=menu.id
menuDic['menuName']=menu.name
menuDic['menuCountry']=menu.country.name
menuDic['menuDescription']=menu.description
menuDic['menuState']=menu.state
for d in DishMenuRels.select().where(menu = menu.id).join(Dishes).join(DishTypes).order_by((DishTypes,'name')):
menuDic[str(d.dish.id)] = {}
menuDic[str(d.dish.id)]['dishTypeName'] = d.dish.dishType.name
menuDic[str(d.dish.id)]['dishTypeId'] = d.dish.dishType.id
menuDic[str(d.dish.id)]['dishId'] = d.dish.id
menuDic[str(d.dish.id)]['dishName'] = d.dish.name
menuDic[str(d.dish.id)]['dishPrice'] = d.dish.price
menuArray.append(menuDic)
return json.dumps(menuArray)
This is my Objectiv-C code in order to get the DataJson and put it in an Array:
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
switch (streamEvent) {
case NSStreamEventOpenCompleted:
[[ConnectionSingleton getInstance] setConnectionMade:YES];
NSLog(#"Stream opened");
break;
case NSStreamEventHasBytesAvailable:
if (theStream == inputStream) {
uint8_t buffer[1024];
int len;
while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
output = [output substringToIndex:[output length] - 2];
if (nil != output) {
NSError* error; // Obligatoir pour le JSON
menu = [NSJSONSerialization JSONObjectWithData:[output dataUsingEncoding:NSUTF8StringEncoding] options:
NSJSONReadingMutableContainers error:&error]; // Put Json in the Array
[[self tableView] reloadData]; // Reload Array to populate it
}
}
}
}
break;
case NSStreamEventErrorOccurred:
NSLog(#"Can not connect to the host!");
break;
case NSStreamEventEndEncountered:
break;
default:
NSLog(#"Unknown event");
}
}
I think this should do the trick
NSArray *firstArray = [NSArray arrayWithObjects:[NSArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",nil], [NSArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",nil],[NSArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",nil],[NSArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",nil],[NSArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",nil],#"String",#"String",#"String",#"String",#"String",nil];
NSInteger count_i = firstArray.count;
NSInteger count_j;
id val;
for (NSInteger i = 0; i < count_i; i++) {
if ([[firstArray objectAtIndex:i] isKindOfClass:[NSArray class]]) {
count_j = [[firstArray objectAtIndex:i] count];
for (NSUInteger j = 0; j < count_j; j++) {
val = [[firstArray objectAtIndex:i] objectAtIndex:j];
NSLog(#"%#",val);
}
}else{
val = [firstArray objectAtIndex:i];
NSLog(#"%#",val);
}
}
But your values are of different types, so you have to deal with them in different ways depending of the value of j.
I am working on a App that makes use of a JSON API and I am Using the JSON for Objective C Framework to get the Data into a NSDictionary. The dictionary loos like this:
({
admitted = "<null>";
agreed = "<null>";
"area_id" = 1;
"area_name" = "Digitales, Urheber-/Patentrecht, Datenschutz";
created = "2010-08-17 12:41:03";
"current_draft_content" = Bla Bla Bla";
"current_draft_created" = "2010-08-17 12:42:44";
"current_draft_formatting_engine" = compat;
"discussion_url" = "http://piratenpad.de/OpenSourceZwang";
id = 502;
"informed_supporter_count" = 11;
"issue_accepted" = "";
"issue_admission_time" = "8 days";
"issue_closed" = "";
"issue_created" = "2010-08-17 12:41:03";
"issue_discussion_time" = "15 days";
"issue_fully_frozen" = "";
"issue_half_frozen" = "";
"issue_id" = 242;
"issue_population" = 372;
"issue_ranks_available" = 0;
"issue_state" = new;
"issue_verification_time" = "8 days";
"issue_vote_later" = 0;
"issue_vote_now" = 0;
"issue_voter_count" = "<null>";
"issue_voting_time" = "8 days";
name = "Alte & unsupportete Software, muss Open Source werden";
"negative_votes" = "<null>";
"policy_initiative_quorum_den" = 100;
"policy_initiative_quorum_num" = 10;
"policy_issue_quorum_den" = 100;
"policy_issue_quorum_num" = 10;
"policy_majority_den" = 2;
"policy_majority_num" = 1;
"policy_majority_strict" = 1;
"positive_votes" = "<null>";
rank = "<null>";
revoked = "<null>";
"satisfied_informed_supporter_count" = 7;
"satisfied_supporter_count" = 7;
"suggested_initiative_id" = "<null>";
"supporter_count" = 11;
},
{
admitted = "<null>";
agreed = "<null>";
"area_id" = 1;
"area_name" = "Digitales, Urheber-/Patentrecht, Datenschutz";
created = "2010-08-17 14:09:14";
"current_draft_content" = "Bla Bla Bla";
"current_draft_created" = "2010-08-17 14:09:31";
"current_draft_formatting_engine" = compat;
"discussion_url" = "";
id = 508;
"informed_supporter_count" = 0;
"issue_accepted" = "2010-08-14 01:51:45";
"issue_admission_time" = "15 days";
"issue_closed" = "";
"issue_created" = "2010-08-14 01:34:26";
"issue_discussion_time" = "30 days";
"issue_fully_frozen" = "";
"issue_half_frozen" = "";
"issue_id" = 30;
"issue_population" = 603;
"issue_ranks_available" = 0;
"issue_state" = accepted;
"issue_verification_time" = "15 days";
"issue_vote_later" = 9;
"issue_vote_now" = 0;
"issue_voter_count" = "<null>";
"issue_voting_time" = "15 days";
name = "Grundrecht: Alternative Formulierung";
"negative_votes" = "<null>";
"policy_initiative_quorum_den" = 100;
"policy_initiative_quorum_num" = 10;
"policy_issue_quorum_den" = 100;
"policy_issue_quorum_num" = 10;
"policy_majority_den" = 3;
"policy_majority_num" = 2;
"policy_majority_strict" = 0;
"positive_votes" = "<null>";
rank = "<null>";
revoked = {
};
"satisfied_informed_supporter_count" = 0;
"satisfied_supporter_count" = 0;
"suggested_initiative_id" = "<null>";
"supporter_count" = 0;
}
)
What is a good way to get all object where the "issue_id" is 2 oder 6 or what ever to display a grouped UITabeView with all objects with the same "issue_id" in one group?
You can use NSSortDescriptor to sort:
NSSortDescriptor *dateSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:#"issue_id" ascending:YES selector:#selector(compare:)] autorelease];
[youDictionaryArray sortUsingDescriptors:[NSArray arrayWithObjects:dateSortDescriptor, nil]];
And/or NSPredicate to get some ID only:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"(issue_id == %i)", 2];
NSArray *newArray = [youDictionaryArray filteredArrayUsingPredicate:predicate];
There are several ways. You can use NSPredicate and use the NSArray method -filteredArrayUsingPredicate:. Or on iOS 4 you use a filtering block: -indexesOfObjectsPassingTest: then use -objectsAtIndexes: to get the objects.
Otherwise the best is you just iterate through the array and filter the items you want into a new one:
// Given a NSArray *items
NSMutableArray *filteredItems = [NSMutableArray array];
for (NSDictionary *item in items) {
if (/* your condition */) {
[filteredItems addObject: item];
}
}