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];
}
Related
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.
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.
Hello I am parsing a RSS And Atom feeds, and my question is how can I check for < img > and < url > tags in < description >?
There must be some sort of check. Thanks.
Here is how I parse them:
- (NSArray *)parseFeed:(NSURL *)feedURL{
NSError *error;
NSData *data = [NSData dataWithContentsOfURL:feedURL];
GDataXMLDocument *xmlParse = [[GDataXMLDocument alloc] initWithData:data error:&error];
GDataXMLElement *rootElement = xmlParse.rootElement;
NSArray *array = [[NSArray alloc] init];
if ([rootElement.name compare:#"rss"] == NSOrderedSame) {
array = [self parseRSSFeed:rootElement];
return array;
} else if ([rootElement.name compare:#"feed"] == NSOrderedSame) {
array = [self parseAtomFeed:rootElement];
return array;
} else {
NSLog(#"Unsupported root element: %#", rootElement.name);
return nil;
}
}
-(NSArray *)parseRSSFeed:(GDataXMLElement *) rootElement
{
NSMutableArray *entries = [[NSMutableArray alloc] init];
NSArray *channels = [rootElement elementsForName:#"channel"];
for (GDataXMLElement *channel in channels) {
NSArray *items = [channel elementsForName:#"item"];
for (GDataXMLElement *item in items) {
FeedItem *itemF = [[FeedItem alloc] init];
itemF.title = [item valueForChild:#"title"];
itemF.description = [item valueForChild:#"description"];
NSLog(#"IMAGE - %#", [item valueForChild:#"img"]);
itemF.dateString = [item valueForChild:#"pubDate"];
itemF.link = [NSURL URLWithString:[item valueForChild:#"link"]];
itemF.dateString = [item valueForChild:#"updated"];
itemF.author = [item valueForChild:#"author"];
[entries addObject:itemF];
NSLog(#"RSS - %#", itemF.title);
}
}
NSArray *RSSArray = [entries copy];
return RSSArray;
}
-(NSArray *)parseAtomFeed:(GDataXMLElement *) rootElement
{
NSMutableArray *entries = [[NSMutableArray alloc] init];
NSArray *entry = [rootElement elementsForName:#"entry"];
for (GDataXMLElement *entryElement in entry) {
// NSArray *items = [channel elementsForName:#"item"];
//for (GDataXMLElement *item in items) {
FeedItem *itemF = [[FeedItem alloc] init];
itemF.title = [entryElement valueForChild:#"title"];
itemF.description = [entryElement valueForChild:#"summary"];
NSArray *links = [entryElement elementsForName:#"link"];
for (GDataXMLElement *link in links) {
itemF.link = [NSURL URLWithString:[[link attributeForName:#"href"] stringValue]];
}
itemF.dateString = [entryElement valueForChild:#"updated"];
NSArray *authors = [entryElement elementsForName:#"author"];
for (GDataXMLElement *authorElement in authors) {
itemF.author = [authorElement valueForChild:#"name"];
}
[entries addObject:itemF];
NSLog(#"Atom - %#", itemF.title);
}
NSArray *atomArray = [entries copy];
return atomArray;
}
I am parsing them using GDataXMLParser, and my own parser class.
Do it like this:
NSString *Str=[item valueForChild:#"description"];
NSArray *tmp=[Str componentsSeparatedByString:#"<Img>"];
if([tmp count]>1){
NSString *urlstr=[[tmp objectatindex:1] stringByReplacingOccurrencesOfString:#" </Img>" withString:#""];
}
Now urlstr contains your image url.
Enjoy
I thought that
itemF.description = [item valueForChild:#"description"];
is NSString. So you can use componentsSeparatedByString with "your tag".
It will return array. In array at postion 1 you will get your img url.
This url has closing bracket "your closing tag".
Replace "your closing tag" with space. You will get image url.
Hope, this will help you.
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
-(void) readRestaurantFromXml {
SGAAppDelegate *app = (SGAAppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *myRequestString = [NSString stringWithFormat:#"%#getXml.aspx",app.SERVER_URL];
NSURL *url = [NSURL URLWithString: myRequestString];
CXMLDocument *rssParser = [[[CXMLDocument alloc] initWithContentsOfURL:url options:0 error:nil] autorelease];
resultNodes = [rssParser nodesForXPath:#"//item" error:nil];
listOfItems = [[NSMutableArray alloc] init];
for (CXMLElement *resultElement in resultNodes) {
NSString *theatre_id = [[resultElement childAtIndex:0] stringValue];
NSString *theatre_name = [[resultElement childAtIndex:1] stringValue];
NSString *restaurant_id = [[resultElement childAtIndex:2] stringValue];
NSString *restaurant_name = [[resultElement childAtIndex:3] stringValue];
NSString *restaurant_desc = [[resultElement childAtIndex:4] stringValue];
NSString *deal_avail = [[resultElement childAtIndex:5] stringValue];
NSString *deal_details = [[resultElement childAtIndex:6] stringValue];
Restaurant *workVal = [[Restaurant alloc] initWithRestTitle:restaurant_name restDesc:restaurant_desc theatreId:theatre_id theatreName:theatre_name restId:restaurant_id restDeals:deal_avail restDealDesc:deal_details];
[listOfItems addObject:workVal];
[workVal release];
}
}
-(void)myTask{
NSLog(#"%d",[listOfItems count]);
}
The NSMutableArray listofItems has 3 values.So how can i extract the array value in another method?
Help me
Fast enumeration is the preferred method.
for (id object in listOfItems) {
//Do something...
}
If you want a single object at an index:
id object = [listOfItems objectAtIndex:someIndex];
If you just want an object (expecting the array to have a single object:
id object = [listOfItems lastObject];
for(int i=0; i < [listOfItems count]; ++i) {
Restaurant* r = [listofItems objectAtIndex:i];
}