How can I create image of google chart in objective c - iphone

I was looking for some ready code so I could insert my data, labels etc. into a function and receive a ready google-chart like this.
But I didn't find any. Any ideas?

In the mean time, I wrote a function that receive all the necessary parameters, creates a google chart and converts it UIImage. Here it is:
-(UIImage )produceGoogleChartImage:(NSString)title
xAxis:(NSArray*)axisXLabels
yAxis:(NSArray*)axisYLabels
andData:(NSArray*)dataValues
color:(NSString*)lineColor
chartWidth:(NSNumber*)width
chartHight:(NSNumber*)hight
lagendLabel:(NSString*)legend
minScale:(NSNumber*)minScale
maxScale:(NSNumber*)maxScale{
NSMutableString *myurl = [NSMutableString stringWithString:#"http://chart.googleapis.com/chart?chxl=0:|"];
//axisXLabels
int countAxisXLabels = [axisXLabels count];
for(NSUInteger i = 0; i < countAxisXLabels; ++i)
{
NSNumber *value = [axisXLabels objectAtIndex:i];
[myurl appendFormat:#"%#", value];
if(i < countAxisXLabels - 1)
[myurl appendString:#"|"];
}
[myurl appendString:#"|1:|"];
//axisYLabels
int countAxisYLabels = [axisYLabels count];
for(NSUInteger i = 0; i < countAxisYLabels; ++i)
{
NSNumber *value = [axisYLabels objectAtIndex:i];
[myurl appendFormat:#"%#", value];
if(i < countAxisYLabels - 1)
[myurl appendString:#"|"];
}
[myurl appendString:#"&chxr=0,0,105|1,3.333,100&chxt=x,y&chs="];
//size
[myurl appendFormat:#"%#x%#&cht=lc&chd=t:", width,hight];
//dataValues
int countDataValues = [dataValues count];
for(NSUInteger i = 0; i < countDataValues; ++i)
{
NSNumber *value = [dataValues objectAtIndex:i];
[myurl appendFormat:#"%#", value];
if(i < countDataValues - 1)
[myurl appendString:#","];
}
//legend
[myurl appendFormat:#"&chdl=%#&chg=25,50&chls=2&",legend];
//color
[myurl appendFormat:#"chm=o,%#,0,-2,8&chco=%#",lineColor,lineColor];
//title
[myurl appendFormat:#"&chtt=+%#",title];
//scale
[myurl appendFormat:#"&chds=%#,%#",minScale,maxScale];
NSString *theurl=[myurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:theurl]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLResponse* response;
NSError* error;
NSData *imageData=[NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response
error:&error];
NSLog(#"%#",error);
NSLog(#"%#",response);
NSLog(#"%#",imageData);
UIImage *myimage = [[UIImage alloc] initWithData:imageData];
return myimage;
// Chart Wizard: https://developers.google.com/chart/image/docs/chart_wizard
}
And here is the test function:
-(void)test{
NSString* title = #"Height History";
NSArray *axisXLabels = [NSArray arrayWithObjects:
#"Jan",
#"Feb",
#"Mar",
#"Jun",
#"Jul",
#"Aug",
nil];
NSArray *axisYLabels = [NSArray arrayWithObjects:
[NSNumber numberWithInt:0],
[NSNumber numberWithInt:50],
[NSNumber numberWithInt:150],
[NSNumber numberWithInt:200],
nil];
NSArray *dataValues = [NSArray arrayWithObjects:
[NSNumber numberWithInt:130],
[NSNumber numberWithInt:140],
[NSNumber numberWithInt:140],
[NSNumber numberWithInt:150],
[NSNumber numberWithInt:170],
[NSNumber numberWithInt:180],
nil];
NSString *lineColor = #"FF9900";
NSNumber *width = [NSNumber numberWithInt:300];
NSNumber *hight = [NSNumber numberWithInt:200];
NSNumber *minScale = [NSNumber numberWithInt:0];
NSNumber *maxScale = [NSNumber numberWithInt:200];
NSString *legendLabel = #"cm";
UIImage *myimage =[self produceGoogleChartImage:title xAxis:axisXLabels yAxis:axisYLabels andData:dataValues color:lineColor
chartWidth:width chartHight:hight lagendLabel:legendLabel
minScale:minScale maxScale:maxScale];
_chartImage.image=myimage;
}
You should get image, like the one in the question.

Related

Memory leak in ios when fetching data from XML

is there any generic approach to fix this kind of memory leaks in ios application.
I am fetching 5000 images from server and saving then in document directory while saving their path in core data.
here is code
-(void)connectionDidFinishLoading:(NSURLConnectionWithTag *)connection
{
NSNumber* nn66 = [NSNumber numberWithInt:2];
if ([nn66 isEqualToNumber:connection.tag])
{
NSXMLDocument* rElement = [[NSXMLDocument alloc] initWithData:[dataFromConnectionsByTag objectForKey:connection.tag] options:0 error:nil];
NSXMLElement* element = [rElement rootElement];
NSArray* shadowElement3 = [element elementsForName:#"PRODUCT_NAME"];
for (int i = 0; i < [shadowElement3 count]; i++)
{
#autoreleasepool
{
NSMutableArray* array = [[NSMutableArray alloc] init];
Product* failedBankInfo = [NSEntityDescription insertNewObjectForEntityForName:#"Product" inManagedObjectContext:context];
NSXMLElement* element11 = [shadowElement3 objectAtIndex:i];
NSString* strPath = [element11 stringValueForNode:#"B1_COD"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:strPath];
[array addObject:savedImagePath];
if (getimages == NO)
{
//**************************************************
NSData* receivedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[element11 stringValueForNode:#"img"]]];
[receivedData writeToFile:savedImagePath atomically:YES];
//**************************************************
//**************************************************
int testNo = ((i+1)*100)/[shadowElement3 count];
NSMutableDictionary* dic = [[NSMutableDictionary alloc] initWithDictionary:[tableDataArray objectAtIndex:lineNo]];
[dic setObject:[NSString stringWithFormat:#"%d",[[NSNumber numberWithInt:testNo] intValue]] forKey:#"status"];
[dic setObject:[NSString stringWithFormat:#"%#",[self onlyDateFromDate:[NSDate date]]] forKey:#"syncDate"];
[dic setObject:[NSString stringWithFormat:#"%d/%d",[[NSNumber numberWithInt:i+1] intValue],[[NSNumber numberWithInt:[shadowElement3 count]] intValue]] forKey:#"totalloaded"];
[tableDataArray replaceObjectAtIndex:lineNo withObject:dic];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"settingdata"];
[[NSUserDefaults standardUserDefaults] setObject:tableDataArray forKey:#"settingdata"];
[_mtable reloadData];
// [self performSelectorInBackground:#selector(ricaelleupdatecompleted:) withObject:dic];
[NSThread detachNewThreadSelector:#selector(ricaelleupdatecompleted:) toTarget:self withObject:dic];
//**************************************************
}
else
{
NSString* newImagePath = [NSString stringWithFormat:#"%#_t",strPath];
NSString *savedImagePath1 = [documentsDirectory stringByAppendingPathComponent:newImagePath];
[array addObject:savedImagePath1];
int testNo = ((i+1)*100)/[shadowElement3 count];
NSMutableDictionary* dic = [[NSMutableDictionary alloc] initWithCapacity:0];
[dic setObject:[NSString stringWithFormat:#"%d%# Completo",[[NSNumber numberWithInt:testNo] intValue],#"%"] forKey:#"status"];
[dic setObject:[NSString stringWithFormat:#"%#",[self onlyDateFromDate:[NSDate date]]] forKey:#"syncDate"];
[dic setObject:[NSString stringWithFormat:#"%d/%d",[[NSNumber numberWithInt:i+1] intValue],[[NSNumber numberWithInt:[shadowElement3 count]] intValue]] forKey:#"totalloaded"];
[NSThread detachNewThreadSelector:#selector(allimagesCompleted:) toTarget:self withObject:dic];
}
failedBankInfo.images = array;
failedBankInfo.DA1_FILIAL = [element11 stringValueForNode:#"DA1_FILIAL"];
failedBankInfo.DA1_CODTAB = [element11 stringValueForNode:#"DA1_CODTAB"];
failedBankInfo.DA1_CODPRO = [element11 stringValueForNode:#"DA1_CODPRO"];
failedBankInfo.DA1_ITEM = [element11 stringValueForNode:#"DA1_ITEM"];
failedBankInfo.DA1_PRCVEN = #"100"; //[element11 stringValueForNode:#"DA1_PRCVEN"];
failedBankInfo.DA1_X_PROM = #"10"; //[element11 stringValueForNode:#"DA1_X_PROM"];
failedBankInfo.DA1_X_ALTE = [element11 stringValueForNode:#"DA1_X_ALTE"];
failedBankInfo.DA1_X_PRFI = [element11 stringValueForNode:#"DA1_X_PRFI"];
failedBankInfo.B2_FILIAL = [element11 stringValueForNode:#"B2_FILIAL"];
failedBankInfo.B2_COD = [element11 stringValueForNode:#"B2_COD"];
failedBankInfo.B2_LOCAL = [element11 stringValueForNode:#"B2_LOCAL"];
failedBankInfo.B2_QATU = #"25";// [element11 stringValueForNode:#"B2_QATU"];
failedBankInfo.B1_FILIAL = [element11 stringValueForNode:#"B1_FILIAL"];
failedBankInfo.B1_COD = [element11 stringValueForNode:#"B1_COD"];
failedBankInfo.B1_DESC = strPath;
failedBankInfo.B1_TIPO = [element11 stringValueForNode:#"B1_TIPO"];
failedBankInfo.B1_UM = [element11 stringValueForNode:#"B1_UM"];
failedBankInfo.B1_LOCPAD = [element11 stringValueForNode:#"B1_LOCPAD"];
failedBankInfo.B1_GRUPO = [element11 stringValueForNode:#"B1_GRUPO"];
failedBankInfo.B1_IPI = [element11 stringValueForNode:#"B1_IPI"];
failedBankInfo.B1_POSIPI = [element11 stringValueForNode:#"B1_POSIPI"];
failedBankInfo.B1_ALTER = [element11 stringValueForNode:#"B1_ALTER"];
failedBankInfo.B1_X_ALT_P = [element11 stringValueForNode:#"B1_X_ALT_P"];
failedBankInfo.B1_X_LAR_P = [element11 stringValueForNode:#"B1_X_LAR_P"];
failedBankInfo.B1_X_COM_P = [element11 stringValueForNode:#"B1_X_COM_P"];
failedBankInfo.B1_PESO = [element11 stringValueForNode:#"B1_PESO"];
failedBankInfo.B1_PESBRU = [element11 stringValueForNode:#"B1_PESBRU"];
failedBankInfo.B1_X_ALT_C = [element11 stringValueForNode:#"B1_X_ALT_C"];
failedBankInfo.B1_X_LAR_C = [element11 stringValueForNode:#"B1_X_LAR_C"];
failedBankInfo.B1_X_COM_C = [element11 stringValueForNode:#"B1_X_COM_C"];
failedBankInfo.B1_X_DIA_P = [element11 stringValueForNode:#"B1_X_DIA_P"];
failedBankInfo.B1_X_DIA_C = [element11 stringValueForNode:#"B1_X_DIA_C"];
failedBankInfo.B1_X_PLI_C = [element11 stringValueForNode:#"B1_X_PLI_C"];
failedBankInfo.B1_X_PBR_C = [element11 stringValueForNode:#"B1_X_PBR_C"];
failedBankInfo.B1_X_ALT_M = [element11 stringValueForNode:#"B1_X_ALT_M"];
failedBankInfo.B1_X_LAR_M = [element11 stringValueForNode:#"B1_X_LAR_M"];
failedBankInfo.B1_X_COM_M = [element11 stringValueForNode:#"B1_X_COM_M"];
failedBankInfo.B1_X_DIA_M = [element11 stringValueForNode:#"B1_X_DIA_M"];
failedBankInfo.B1_X_PBR_M = [element11 stringValueForNode:#"B1_X_PBR_M"];
failedBankInfo.B1_X_PLI_M = [element11 stringValueForNode:#"B1_X_PLI_M"];
failedBankInfo.B1_X_PGCAT = [NSNumber numberWithInt:[[element11 stringValueForNode:#"B1_X_PGCAT"] intValue]];
failedBankInfo.B1_X_CXMAS = [element11 stringValueForNode:#"B1_X_CXMAS"];
failedBankInfo.B1_CODBAR = [element11 stringValueForNode:#"B1_CODBAR"];
failedBankInfo.B1_X_DUN14 = [element11 stringValueForNode:#"B1_X_DUN14"];
failedBankInfo.B1_TS = [element11 stringValueForNode:#"B1_TS"];
failedBankInfo.B1_TE = [element11 stringValueForNode:#"B1_TE"];
failedBankInfo.B1_X_DESCR = [element11 stringValueForNode:#"B1_X_DESCR"];
failedBankInfo.B1_QE = [NSNumber numberWithInt:4]; //[[element11 stringValueForNode:#"B1_QE"] intValue]]; //[eleme
NSError *error;
if (![context save:&error])
{
NSLog(#"error occured");
}
else
{
NSLog(#"clientes Saved copupons");
}
}
}
}
[SVProgressHUD dismiss];
if (getimages == NO)
{
[SVProgressHUD showWithStatus:#"Please wait we are processing images"];
[self performSelector:#selector(complieImage) withObject:nil afterDelay:.1];
}
NSNumber* nnn = [NSNumber numberWithInt:3];
if ([connection.tag isEqualToNumber:nnn])
{
[self saveClientTableData:nnn];
}
NSNumber* nn5 = [NSNumber numberWithInt:5];
if ([nn5 isEqualToNumber:connection.tag])
{
[self saveBannerData:nn5];
}
[SVProgressHUD dismiss];
[Utils readAllCoreData];
[dataFromConnectionsByTag removeObjectForKey:connection.tag];
}

CoreData inserting very huge DB exc_bad_access

I have ~60000 values in my DB.
I must to keep them all. But while inserting values I get exc_bad_access.
Here is my code:
if (context == nil)
{
context = [(radioAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSLog(#"After managedObjectContext: %#", context);
}
[self performSelectorOnMainThread:#selector(deleteAllFromDB) withObject:nil waitUntilDone:YES];
// here is JSON parsing
int i=0;
#synchronized(self)
{
NSLog(#"Start");
NSEntityDescription *entity = [[NSEntityDescription entityForName:#"Station" inManagedObjectContext:context] autorelease];
for (NSString*string in stations)
{
if (![string isEqualToString:#""])
{
Station*station = [[[Station alloc] initWithEntity:entity insertIntoManagedObjectContext:nil] retain];
NSError *err = nil;
id parsedData = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers error:&err];
if (err) {
NSLog(#"error is %#", [err localizedDescription]);
}
[station setName:[parsedData objectForKey:#"nm"]];
[station setBit: [parsedData objectForKey:#"btr"]];
[station setEnabled: [NSNumber numberWithInt:1]];
//encoding id of the station
scanner = [NSScanner scannerWithString:[parsedData objectForKey:#"id"]];
[scanner scanHexInt:&tempInt];
NSNumber *numb = [[NSNumber alloc]initWithInt:i];
[station setNumber: [NSNumber numberWithInt:[numb intValue]]];
//encoding country ID
numb = [NSNumber numberWithInt:i];
[station setCountryID: [NSNumber numberWithInt:[numb intValue]]];
//encoding genre ID
numb = [NSNumber numberWithInt:i];
[station setGenerID:[NSNumber numberWithInt:[numb intValue]]];
[station setOrder:[NSNumber numberWithInt:i]];
[context insertObject:station];
float k = [stations count];
k = (i + 1)/k;
[self performSelectorOnMainThread:#selector(increaseProgress:) withObject:[NSNumber numberWithFloat:k] waitUntilDone:YES];
i++;
[scanner release];
[numb release];
[station release];
[parsedData release];
}
}
[context save:nil];
[entity release];
NSLog(#"Stop");
NSEntityDescription *entityGen = [NSEntityDescription entityForName:#"Genre" inManagedObjectContext:context];
NSURL* urlForGenre = [NSURL URLWithString:#"xxx.xxx"];
NSData *genres = [[NSData alloc] initWithContentsOfURL:urlForGenre];
NSError *err = nil;
NSArray *parsedGenres = [NSJSONSerialization JSONObjectWithData:genres options:NSJSONReadingMutableContainers error:&err];
if (err)
{
NSLog(#"error is %#", [err localizedDescription]);
}
for (int i =0; i<parsedGenres.count; i++)
{
Genre*gen = [[Genre alloc] initWithEntity:entityGen insertIntoManagedObjectContext:nil];
gen.name = [[parsedGenres objectAtIndex:i] objectForKey:#"nm"];
int tempInt;
NSScanner *scanner= [[NSScanner alloc] init];
scanner = [NSScanner scannerWithString:[[parsedGenres objectAtIndex:i] objectForKey:#"id"]];
[scanner scanInt:&tempInt];
NSNumber *numb = [[NSNumber alloc] init];
numb = [NSNumber numberWithInt:tempInt];
gen.number = [NSNumber numberWithInt:[numb integerValue]];
float k = [parsedGenres count];
k = (i + 1)/k;
[self performSelectorOnMainThread:#selector(increaseProgress:) withObject:[NSNumber numberWithFloat:k] waitUntilDone:YES];
[context insertObject:gen];
[gen release];
}
[entityGen release];
[context save:nil];
NSEntityDescription *entityCon = [NSEntityDescription entityForName:#"Country" inManagedObjectContext:context];
NSURL* urlForCoun = [NSURL URLWithString:#"yyy.yyy"];
NSData *countr = [[NSData alloc] initWithContentsOfURL:urlForCoun];
err = nil;
NSArray *parsedCountr = [NSJSONSerialization JSONObjectWithData:countr options:NSJSONReadingMutableContainers error:&err];
if (err)
{
NSLog(#"error is %#", [err localizedDescription]);
}
NSMutableArray* temp = [[NSMutableArray alloc] init];
for (int i =0; i<parsedCountr.count; i++)
{
Country*countr = [countr initWithEntity:entityCon insertIntoManagedObjectContext:nil];
countr.name = [[parsedCountr objectAtIndex:i] objectForKey:#"nm"];
int tempInt;
NSScanner *scanner= [[NSScanner alloc] init];
scanner = [NSScanner scannerWithString:[[parsedCountr objectAtIndex:i] objectForKey:#"id"]];
[scanner scanInt:&tempInt];
NSNumber *numb = [[NSNumber alloc] init];
numb = [NSNumber numberWithInt:tempInt];
countr.number = [NSNumber numberWithInt:[numb integerValue]];
[temp addObject:countr];
float k = [parsedCountr count];
k = (i + 1)/k;
[self performSelectorOnMainThread:#selector(increaseProgress:) withObject:[NSNumber numberWithFloat:k] waitUntilDone:YES];
[context insertObject:countr];
[countr release];
}
[context save:nil];
If my app doesn't crash, yes, it happens not by every launch. It crashes on:
Country*countr = [countr initWithEntity:entityCon insertIntoManagedObjectContext:nil];
Please help! And sorry for my terrible English.
Update:
On:
Country*countr = [countr initWithEntity:entityCon insertIntoManagedObjectContext:nil];
Thread 7: EXC_BAD_ACCESS (code=1, address=0x3f800008)
Other error is exc_bad_access too. But with code=2 and on other thread.
Update 2:
I enabled zombies mode in scheme of my debug. Nothing happened.
Update 3:
I think I have problems with memory.
GuardMalloc: Failed to VM allocate 4128 bytes
GuardMalloc: Explicitly trapping into debugger!!!
You can't pass nil as managedObjectContext parameter to initWithEntity:insertIntoManagedObjectContext: method. Try changing this:
Country*countr = [countr initWithEntity:entityCon insertIntoManagedObjectContext:nil];
to this
// pass managed object context parameter
Country*countr = [countr initWithEntity:entityCon insertIntoManagedObjectContext:context];
Based on the documentation and my experience you can pass nil as managedObjectContext.
I was also getting an EXC_BAD_ACCESS and it came that the reason was that I was not retaining the managed object model(I was only creating a model to get the entity description and then it was released).
In particular, this is what I was doing:
In a test class, in the setUp method:
- (void)setUp
{
[super setUp];
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
NSURL *modelURL = [bundle URLForResource:#"TestDatamodel" withExtension:#"momd"];
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
STAssertNotNil(model, nil);
_entity = [[model entitiesByName] objectForKey:NSStringFromClass([MyEntity class])];
STAssertNotNil(_entity, nil);
// ...
}
Then in a test method I was creating a managed object without a context like this:
NSManagedObject *object = [[NSManagedObject alloc] initWithEntity:_entity insertIntoManagedObjectContext:nil];
And I was getting EXC_BAD_ACCESS here.
The solution was to add an ivar to the test class to keep a reference to the managed object model.

iphone+UIscrollview or to use uitableview to display image in matrix format

I want to display the image(which comes from webservice) the format such that the output in the screen appears like below image:-
Now the logic i had implemented is,i had added the image in uiscrollview.
with the below logic:-
for (int j=0;j<9;j++) {
for (int i=0; i<[mainRestaurantArray count];i++) {
if ([[[mainRestaurantArray objectAtIndex:i] valueForKey:#"Image"] isKindOfClass:[UIImage class]]) {
[CombineArray addObject:[mainRestaurantArray objectAtIndex:i]];
//NSLog(#"cnt=>%d array==>%#",cnt,[CombineArray objectAtIndex:cnt]);
UIButton* btn = [[UIButton alloc]init];
btn.tag = cnt;
btn.frame = CGRectMake(15+(cnt%5)*60, 15+(cnt/5)*60,Width,Height);
btn.backgroundColor = [UIColor greenColor];
[btn setBackgroundImage:[[CombineArray objectAtIndex:cnt] valueForKey:#"Image"] forState:UIControlStateNormal];
[btn addTarget:self action:#selector(Buttonclick:) forControlEvents:UIControlEventTouchUpInside];
[ScrlPhotos addSubview:btn];
[btn release];
cnt++;
}
}
[mainRestaurantArray release];
counter++;
[self urlcalled];//The function which calls the webservice
}
//}
ScrlPhotos.contentSize = CGSizeMake(320, ([CombineArray count]/5.0)*60+25);
The function which does the webservice is below:-
-(void)urlcalled{
#try
{
if (rangeDistance == nil) {
rangeDistance =#"100";
}
urlstring[0]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Gym&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[1]=[NSString stringWithFormat:#"http://www.google.com/maps?q=resort&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[2]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Tourist place&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[3]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Hotels&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[4]=[NSString stringWithFormat:#"http://www.google.com/maps?q=shopping Mall&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[5]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Industries&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[6]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Shopping_mall&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[7]=[NSString stringWithFormat:#"http://www.google.com/maps?q=garden&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[8]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Religious Place&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[9]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Restaurants&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
NSLog(#"conte==>%d urlstring[counter]==>%#",counter,urlstring[counter]);
NSString *str = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlstring[counter]]];
str1 = [str substringFromIndex:9];
//NSLog(#"===>%#",str1);
NSArray *array = [str1 componentsSeparatedByString:#"overlays:"];
NSString *str2 = [array objectAtIndex:1];
NSString *finalUpperStr = [str2 substringFromIndex:21];
array1 = [finalUpperStr componentsSeparatedByString:#"},panel:"];
NSString *strF = [array1 objectAtIndex:0];
NSArray *arrayF = [strF componentsSeparatedByString:#"{id:"];
///////....................this object will change as require in for loop .............................//
mainRestaurantArray = [[NSMutableArray alloc] init];
for (int i=1; i<[arrayF count]-5; i++) {
NSString *strF12 = [arrayF objectAtIndex:i];
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
NSArray *aryF23 = [strF12 componentsSeparatedByString:#"latlng:{"];
//NSLog(#"%#",[aryF23 objectAtIndex:1]);
NSString *strF23 = [aryF23 objectAtIndex:1];
NSArray *ar = [strF23 componentsSeparatedByString:#"},image:"];
//NSLog(#"%#",[ar objectAtIndex:0]);
NSString *strLat = [ar objectAtIndex:0];
NSArray *arrayLat = [strLat componentsSeparatedByString:#","];
NSString *strFLat = [[arrayLat objectAtIndex:0] substringFromIndex:4];
NSString *strLong = [[arrayLat objectAtIndex:1] substringFromIndex:4];
//NSLog(#"Lati = %# Longi = %#" , strFLat , strLong);
[dic setValue:strFLat forKey:#"Latitude"];
[dic setValue:strLong forKey:#"Longitude"];
NSString *strLAdd = [ar objectAtIndex:1];
NSArray *arrayLAdd = [strLAdd componentsSeparatedByString:#"laddr:"];
//NSLog(#"%#",[arrayLAdd objectAtIndex:1]);
NSString *strLAdd1 = [arrayLAdd objectAtIndex:1];
NSArray *arrayLAdd1 = [strLAdd1 componentsSeparatedByString:#"geocode:"];
// NSLog(#"%#",[arrayLAdd1 objectAtIndex:0]);
NSString *strAddres = [[arrayLAdd1 objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
//NSLog(#"%#",strAddres);
[dic setValue:strAddres forKey:#"Address"];
NSString *strName = [arrayLAdd1 objectAtIndex:1];
NSArray *arrayName = [strName componentsSeparatedByString:#"name:"];
NSString *strName1 = [[arrayName objectAtIndex:1]stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSArray *arrayName1 = [strName1 componentsSeparatedByString:#"infoWindow:"];
[dic setValue:[arrayName1 objectAtIndex:0] forKey:#"Name"];
// for image load .. 07Dec..
NSString *strImage= [arrayF objectAtIndex:i];
NSRange range = [strImage rangeOfString:#"photoUrl"];
if(range.location == NSNotFound){
NSLog(#"Not found");
[dic setValue:#"" forKey:#"Image"];
}else{
NSArray *arrayImage = [strImage componentsSeparatedByString:#"photoUrl:"];
NSString *strImage1 = [arrayImage objectAtIndex:1];
NSArray *arrayImage1 = [strImage1 componentsSeparatedByString:#",photoType:"];
NSString *strfindImage = [[arrayImage1 objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
myImage = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:strfindImage]]];
[dic setValue:myImage forKey:#"Image"];
}
[mainRestaurantArray addObject:dic];
if (i==20) {
break;
}
}
}
#catch (NSException * e)
{
NSLog(#"NSException==>%#",e);
}
}
But the problem i am facing is the image is displayed after completing the loop at 10 times.
I want to display the image parallely as it comes from webservice,so that time taken should be less..
Is there any way out..
Please help me.
Use UIImageView+cacheWeb.. it makes lazy loading a lot easier
http://hackemist.com/SDWebImage/doc/Categories/UIImageView+WebCache.html

Help with a For loop and NSMutableDictionary

I am using a for loop to (currently) NSLog the contents of a NSArray. However I would like to set the contents of the array into a NSMutableDictionary, depending on the objectAtIndex it is. Currently there are 843 objects in the array, and therefore I would rather not have to type out the same thing over and over again!
My code currently is this
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
string = [string stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSArray *chunks = [string componentsSeparatedByString:#","];
for (int i = 0; i < [chunks count]; i ++) {
NSLog(#"%#", [chunks objectAtIndex:i]);
}
I would like to set the contents of the array into the NSMutableDictionary in the following fashion, and once the objectAtIndex is 11, I would like to set the 12th object in the dictionary to be of the key #"type" and soforth:
[dict setObject:[chunks objectAtIndex:0] forKey:#"type"];
[dict setObject:[chunks objectAtIndex:1] forKey:#"name"];
[dict setObject:[chunks objectAtIndex:2] forKey:#"street"];
[dict setObject:[chunks objectAtIndex:3] forKey:#"address1"];
[dict setObject:[chunks objectAtIndex:4] forKey:#"address2"];
[dict setObject:[chunks objectAtIndex:5] forKey:#"town"];
[dict setObject:[chunks objectAtIndex:6] forKey:#"county"];
[dict setObject:[chunks objectAtIndex:7] forKey:#"postcode"];
[dict setObject:[chunks objectAtIndex:8] forKey:#"number"];
[dict setObject:[chunks objectAtIndex:9] forKey:#"coffee club"];
[dict setObject:[chunks objectAtIndex:10] forKey:#"latitude"];
[dict setObject:[chunks objectAtIndex:11] forKey:#"longitude"];
I'm not sure I fully understand the question, but I think that your chunks array contains a long list of data, ordered in the same way (i.e. 0th, 12th, 24th, 36th... elements are all type, and 1st, 13th, 25th, 37th... elements are all name). If this is the case, you could use something like this:
NSArray *keys = [NSArray arrayWithObjects:#"type", #"name", #"street", #"address1", #"address2", #"town", #"county", #"postcode", #"number", #"coffee club", #"latitude", #"longitude", nil];
for (NSUInteger i = 0; i < [chunks count]; i += [keys count])
{
NSArray *subarray = [chunks subarrayWithRange:NSMakeRange(i, [keys count])];
NSDictionary *dict = [[NSDictionary alloc] initWithObjects:subarray forKeys:keys];
// do something with dict
[dict release];
}
Note that you can't have two different values for the same key with NSDictionary. That is, if you set two different values for the type key, only the last value set will be kept.
Edit
If your array is not a multiple of 12 because for example it contains garbage data at the end, you could use a different looping style instead:
// max should be a multiple of 12 (number of elements in keys array)
NSUInteger max = [chunks count] - ([chunks count] % [keys count]);
NSUInteger i = 0;
while (i < max)
{
NSArray *subarray = [chunks subarrayWithRange:NSMakeRange(i, [keys count])];
NSDictionary *dict = [[NSDictionary alloc] initWithObjects:subarray forKeys:keys];
// do something with dict
[dict release];
i += [keys count];
}
Since there's no pattern to your keys, you're better off doing it manually like you're doing it now.
The most straightforward thing to do would be to use the code you posted. But if you really want to use a loop, something like this should do.
NSArray *keys = [NSArray arrayWithObjects:#"type", #"name", #"street", #"address1", #"address2", #"town", #"county", #"postcode", #"number", #"coffee club", #"latitude", #"longitude", nil];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
string = [string stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSArray *chunks = [string componentsSeparatedByString:#","];
for (int i = 0; i < [chunks count] && i < [keys count]; i ++) {
[dict setObject:[chunks objectAtIndex:i] forKey:[keys objectAtIndex:i]];
}
NSArray* keys = [NSArray arrayWithObjects:#"type",#"name",#"street",#"address1",#"address2",#"town",#"county",#"postcode",#"number",#"coffee club",#"latitude",#"longitude",nil];
for (int i = 0; i < [chunks count]; i ++){
[dict setObject:[chucks objectAtIndex:i] forKey:[keys objectAtIndex:i]];
}

SQLITE Database Error 14

I'm developing a game where there are 4 buildings and in these buildings, there are 3 stages inside. The player can play the stages one by one, from one building to another, however, when they have finished one cycle (eg. going from building 1 stage 1 to building 4 stage 3) I keep getting this error where it's an error 14 (SQLITE_CANTOPEN) whenever the player clicks on another building. It keeps happening every single time I test the app. Can anyone help me? :S
edit: sorry, here's the code I used to open the window to access the game:
NSArray *bldgLevels = [[SQLiteManager sharedManager] fetchDataFromDatabase: MAIN_DATABASE
withQuery: SQL_STMT_GET_BUILDING_LEVELS
withValuesAndTypes: [NSArray arrayWithObjects:
[NSString stringWithFormat: #"%d", gameStateProxy.selectedArea], #"i", nil]];
NSLog(#"bldgLevels: %#", bldgLevels);
NSLog(#"getting player levels");
NSArray *playerLevels = [[SQLiteManager sharedManager] fetchDataFromDatabase: MAIN_DATABASE
withQuery: SQL_STMT_GET_PLAYER_UNLOCKED_LEVELS
withValuesAndTypes: [NSArray arrayWithObjects:
[NSString stringWithFormat: #"%d", gameStateProxy.playerId], #"i", nil]];
NSLog(#"playerLevels: %#", playerLevels);
int i = 0;
while (i < [bldgLevels count])
{
NSDictionary *bldgLevel = (NSDictionary *)[bldgLevels objectAtIndex: i];
int levelId = [(NSNumber *)[bldgLevel objectForKey: #"level_id"] intValue];
int indexOrder = [(NSNumber *)[bldgLevel objectForKey: #"index_order"] intValue];
data = [BldgLevelData createObject];
data.levelId = levelId;
data.levelName = (NSString *)[bldgLevel objectForKey: #"name"];
data.rescuedPtsRequired = [(NSNumber *)[bldgLevel objectForKey: #"rescued_required"] intValue];
data.minPtsToComplete = [(NSNumber *)[bldgLevel objectForKey: #"min_pts"] intValue];
data.lastPlayed = #"";
data.dateAdded = #"";
data.isNew = NO;
data.isCompleted = NO;
data.isLocked = YES;
// Group levels together by their index order
if (indexOrder == 1) { groupId++; }
data.groupId = groupId;
data.indexOrder = indexOrder;
int j = 0;
while (j < [playerLevels count])
{
NSDictionary *playerLevel = (NSDictionary *)[playerLevels objectAtIndex: j];
int playerLevelId = [(NSNumber *)[playerLevel objectForKey: #"level_id"] intValue];
if (levelId == playerLevelId)
{
data.rescuedHighScore = [(NSNumber *)[playerLevel objectForKey: #"rescued_highscore"] intValue];
data.rescuedScore = [(NSNumber *)[playerLevel objectForKey: #"rescued_score"] intValue];
data.lastPlayed = (NSString *)[playerLevel objectForKey: #"lastplayed"];
data.dateAdded = (NSString *)[playerLevel objectForKey: #"dateadded"];
data.isNew = ([(NSString *)[playerLevel objectForKey: #"lastplayed"] isEqualToString: #""]);
data.isCompleted = ([(NSNumber *)[playerLevel objectForKey: #"completed"] intValue] == 1);
data.isLocked = NO;
break;
}
j++;
}
if (indexOrder == 1)
{
list = [NSMutableArray arrayWithCapacity: 1];
groupData = [BldgLevelGroupData createObject];
groupData.groupId = groupId;
groupData.firstLevelId = levelId;
groupData.timeLimit = [(NSNumber *)[bldgLevel objectForKey: #"time_limit"] intValue];
groupData.list = list;
// Get SOS items
NSMutableArray *sosItems = [NSMutableArray arrayWithCapacity: 0];
//
NSLog(#"getting levelSOSItems");
NSLog(#"i: %d, j: %d", i, j);
NSLog(#"list: %#", list);
NSLog(#"levelId: %d", levelId);
NSArray *levelSOSItems = [[SQLiteManager sharedManager] fetchDataFromDatabase: MAIN_DATABASE
withQuery: SQL_STMT_GET_LEVEL_SOS
withValuesAndTypes: [NSArray arrayWithObjects:
[NSString stringWithFormat: #"%d", levelId], #"i", nil]];
NSLog(#"Levelsositems: %#", levelSOSItems);
NSLog(#"getting player sos Items");
NSArray *playerSOSItems = [[SQLiteManager sharedManager] fetchDataFromDatabase: MAIN_DATABASE
withQuery: SQL_STMT_GET_PLAYER_SOS
withValuesAndTypes: [NSArray arrayWithObjects:
[NSString stringWithFormat: #"%d", gameStateProxy.playerId], #"i",
nil]];
NSLog(#"playerSoSItems: %#", playerSOSItems);
j = 0;
while (j < [levelSOSItems count])
{
SOSItemData *sosItemData = [SOSItemData createObject];
sosItemData.itemId = [(NSNumber *)[(NSDictionary *)[levelSOSItems objectAtIndex: j] objectForKey: #"sos_id"] intValue];
sosItemData.itemName = (NSString *)[(NSDictionary *)[levelSOSItems objectAtIndex: j] objectForKey: #"name"];
sosItemData.desc = (NSString *)[(NSDictionary *)[levelSOSItems objectAtIndex: j] objectForKey: #"desc"];
sosItemData.coins = [(NSNumber *)[(NSDictionary *)[levelSOSItems objectAtIndex: j] objectForKey: #"coins_cost"] intValue];
sosItemData.cash = [(NSNumber *)[(NSDictionary *)[levelSOSItems objectAtIndex: j] objectForKey: #"cash_cost"] intValue];
sosItemData.rescuedPtsRequired = [(NSNumber *)[(NSDictionary *)[levelSOSItems objectAtIndex: j] objectForKey: #"rescued_required"] intValue];
int k = 0;
while (k < [playerSOSItems count])
{
if ([(NSNumber *)[(NSDictionary *)[playerSOSItems objectAtIndex: k] objectForKey: #"sos_id"] intValue] == sosItemData.itemId)
{
sosItemData.qty = [(NSNumber *)[(NSDictionary *)[playerSOSItems objectAtIndex: k] objectForKey: #"qty"] intValue];
break;
}
k++;
}
//NSLog(#"%#", sosItemData);
[sosItems addObject: sosItemData];
j++;
}
groupData.sosItems = sosItems;
[groupsList addObject: groupData];
}
NSLog(#"%#", data);
[list addObject: data];
i++;
}
and here's the code I used to fetch the data from the database:
-(NSArray *) fetchDataFromDatabase:(NSString *)dbPath withQuery: (NSString *)sql withValuesAndTypes: (NSArray *)params
{
/*
dbPath - Name of database file
sql - SQL statement. Prepared statements are allowed to be used here (refer to params
params - Array containing data and its corresponding data type
*/
NSMutableArray *result = nil;
//make sure db is closed
NSLog(#"close database first!");
sqlite3_close(database);
NSLog(#"open database!");
int dbStatus = [self openDatabase: dbPath];
if (dbStatus == SQLITE_OK)
{
//int stmtStatus = sqlite3_prepare_v2(database, [sql UTF8String], -1, &stmt, NULL);
int stmtStatus = [self prepareStatement: sql withParams: params];
if(stmtStatus == SQLITE_OK)
{
result = [NSMutableArray arrayWithCapacity: 1];
while(sqlite3_step(stmt) == SQLITE_ROW)
{
NSMutableDictionary *row = [NSMutableDictionary dictionaryWithCapacity: 1];
int columnCount = sqlite3_column_count(stmt);
int j = 0;
while (j < columnCount)
{
/*
Possible sqlite data types:
SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT, SQLITE_BLOB, SQLITE_NULL
*/
if (sqlite3_column_type(stmt, j) == SQLITE_INTEGER)
{
[row setObject: [NSNumber numberWithInt: sqlite3_column_int(stmt, j)]
forKey: [NSString stringWithUTF8String: sqlite3_column_name(stmt, j)]];
}
else if (sqlite3_column_type(stmt, j) == SQLITE_FLOAT)
{
[row setObject: [NSNumber numberWithDouble: sqlite3_column_double(stmt, j)]
forKey: [NSString stringWithUTF8String: sqlite3_column_name(stmt, j)]];
}
else if (sqlite3_column_type(stmt, j) == SQLITE_TEXT)
{
[row setObject: [NSString stringWithFormat: #"%s", sqlite3_column_text(stmt, j)]
forKey: [NSString stringWithUTF8String: sqlite3_column_name(stmt, j)]];
}
else if (sqlite3_column_type(stmt, j) == SQLITE_NULL)
{
[row setObject: [NSNull null]
forKey: [NSString stringWithUTF8String: sqlite3_column_name(stmt, j)]];
}
j++;
}
[result addObject: row];
}
}
else { NSLog(#"stmt error: %d", stmtStatus); }
}
else if (dbStatus == 14)
{
NSLog(#"db error: %d", dbStatus);
NSLog(#"killing app.");
exit(0);
}
else { NSLog(#"db error: %d", dbStatus); }
//Even though the open call failed, close the database connection to release all the memory.
sqlite3_close(database);
return result;
}
sorry if it is wrong..... in your code you didn't finalize statement but useed stmt variable .before close DB ,we should finalize statement if we use statement.....
comment for finalize statement
sqlite3_finalize(Stmt);