Play iPod playlist retrieved from a saved persistentid list - iphone

I saved the persistent ID of the songs selected with media picker, now I'm trying to crate the queue to play that list but something is wrong in this code:
myPlayer = [MPMusicPlayerController applicationMusicPlayer];
NSMutableArray *canzonilist = [[[NSMutableArray alloc] initWithCapacity:1] retain];
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:#"listaCanzoni"];
NSArray *decodedData = [NSKeyedUnarchiver unarchiveObjectWithData:data];
[canzonilist addObjectsFromArray:decodedData];
MPMediaQuery *songQuery = [MPMediaQuery songsQuery];
for (int i = 0; i > [canzonilist count]; i++) {
[songQuery addFilterPredicate:[MPMediaPropertyPredicate predicateWithValue:[canzonilist objectAtIndex:i] forProperty:MPMediaItemPropertyPersistentID]];
}
NSArray *songs = [songQuery items];
MPMediaItemCollection *currentQueue = [[MPMediaItemCollection alloc] initWithItems:songs];
if (currentQueue != nil) {
[myPlayer setQueueWithItemCollection:currentQueue];
} else {
[myPlayer setQueueWithQuery: [MPMediaQuery songsQuery]];
}
[myPlayer play];
[canzonilist release];
[currentQueue release];
Thanks

Finally I found the solution:
SAVE:
- (void) mediaPicker: (MPMediaPickerController *) mediaPicker didPickMediaItems: (MPMediaItemCollection *) mediaItemCollection {
[self savePlaylist:mediaItemCollection];
[self dismissModalViewControllerAnimated: YES];
}
- (void)savePlaylist:(MPMediaItemCollection *) mediaItemCollection {
NSArray* items = [mediaItemCollection items];
NSMutableArray* listToSave = [[NSMutableArray alloc] initWithCapacity:0];
for (MPMediaItem *song in items) {
NSNumber *persistentId = [song valueForProperty:MPMediaItemPropertyPersistentID];
[listToSave addObject:persistentId];
}
NSData *data = [NSKeyedArchiver archivedDataWithRootObject: listToSave];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:#"songsList"];
[[NSUserDefaults standardUserDefaults] synchronize];
[listToSave release];
}
LOAD
- (void)setupMusic {
myPlayer = [MPMusicPlayerController applicationMusicPlayer];
if ([[NSUserDefaults standardUserDefaults] objectForKey:#"songsList"] != nil) {
NSMutableArray *theList = [[NSMutableArray alloc] initWithCapacity:0];
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:#"songsList"];
NSArray *decodedData = [NSKeyedUnarchiver unarchiveObjectWithData:data];
[theList addObjectsFromArray:decodedData];
NSMutableArray *allTheSongs = [[NSMutableArray alloc] initWithCapacity:0];
for (int i = 0; i < [theList count]; i++) {
MPMediaQuery *songQuery = [MPMediaQuery songsQuery];
[songQuery addFilterPredicate:[MPMediaPropertyPredicate predicateWithValue:[theList objectAtIndex:i] forProperty:MPMediaItemPropertyPersistentID]];
NSArray *songs = [songQuery items];
[allTheSongs addObjectsFromArray: songs];
}
MPMediaItemCollection *currentQueue = [[MPMediaItemCollection alloc] initWithItems:allTheSongs];
[myPlayer setQueueWithItemCollection:currentQueue];
[theList release];
[currentQueue release];
[allTheSongs release];
} else {
[myPlayer setQueueWithQuery: [MPMediaQuery songsQuery]];
[myPlayer setShuffleMode: MPMusicShuffleModeSongs]; //optional
}
}

Related

performselectorinBackground is not working

In a view I am showing images which I am fetching from coredata, The images I am showing using carousel classes. In the same view I have facebook button which will navigate me to another screen. When I am clicking the Facebook button then the action is not getting performed, after the images are loaded only the next screen is coming, the button action is not getting called as soon as I click on it.
In viewDidLoad I have called:
[self performSelectorInBackground:#selector(popularImages) withObject:nil];
The popularImages method:
- (void)popularImages
{
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:#"Deals"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"ispopular == 1"];
[request setPredicate:predicate];
NSLog(#"popular Hypes called");
[self.managedObjectContext executeFetchRequest:request returnManagedObjectIDs:NO onSuccess:^(NSArray *deals) {
deals123 = [[NSMutableArray alloc] initWithArray:deals];
ij = 1;
for (Deals *deals in deals123) {
customizedMessage = [deals valueForKeyPath:#"txtmsgrec"];
dealIdString = [deals valueForKeyPath:#"dealsId"];
descriptionStr = [deals valueForKeyPath:#"dealdescription"];
captionStrArray = [deals valueForKeyPath:#"dealsassets.caption"];
[customizedMessageDict setObject:customizedMessage forKey:[NSString stringWithFormat:#"dealid%d",ij]];
[dealDict setObject:customizedMessageDict forKey:#"dealsmessage"];
[dealsIdDict setObject:dealIdString forKey:[NSString stringWithFormat:#"dealid%d",ij]];
[dealDict setObject:dealsIdDict forKey:#"dealsId"];
NSDictionary *dict = [NSDictionary dictionaryWithObject:captionStrArray forKey:#"caption"];
NSArray *captionTemparr = [[dict objectForKey:#"caption"] allObjects];
NSArray *assets = [deals valueForKeyPath:#"dealsassets.dealassetid"];
NSDictionary *dealassetidDict = [NSDictionary dictionaryWithObject:assets forKey:#"dealassetid"];
NSArray *dealassetidTemparr = [[dealassetidDict objectForKey:#"dealassetid"] allObjects];
[dealsUrlDict setObject:[[dealassetidDict objectForKey:#"dealassetid"] allObjects] forKey:[NSString stringWithFormat:#"dealid%d",ij]];
[dealDict setObject:dealsUrlDict forKey:#"delasURL"];
[dealsdescriptionDict setObject:descriptionStr forKey:[NSString stringWithFormat:#"dealid%d",ij]];
[dealDict setObject:dealsdescriptionDict forKey:#"dealsDescription"];
[dealscaptionDict setObject:captionTemparr forKey:[NSString stringWithFormat:#"dealid%d",ij]];
[dealDict setObject:dealscaptionDict forKey:#"dealscaption"];
ij++;
}
NSArray *array = [[dealDict valueForKey:#"delasURL"]allKeys];
NSLog(#"allKeys]class %#",[[[dealDict valueForKey:#"delasURL"]allKeys]class]);
NSDictionary *dealurlDict = [dealDict valueForKey:#"delasURL"];
NSDictionary *dealDescDict = [dealDict valueForKey:#"dealsDescription"];
NSDictionary *dealCaptionDict = [dealDict valueForKey:#"dealscaption"];
NSDictionary *dealIDDict = [dealDict valueForKey:#"dealsId"];
NSDictionary *dealMessageDict = [dealDict valueForKey:#"dealsmessage"];
for(int i=0;i<[array count];i++)
{
NSString *keyvalue = (NSString *)[array objectAtIndex:i];
NSString *dealId = [dealIDDict valueForKey:keyvalue];
NSArray *dealUrl = [dealurlDict valueForKey:keyvalue];
NSString *dealdesc = [dealDescDict valueForKey:keyvalue];
NSArray *dealcaption = [dealCaptionDict valueForKey:keyvalue];
NSString *dealMessage = [dealMessageDict valueForKey:keyvalue];
if([dealUrl count] == [dealcaption count])
{
//[dealUrl enumerateObjectsUsingBlock:^(id obj,NSUInteger idx,BOOL *stop)
for(int j = 0; j<[dealUrl count]; j++)
{
PopularHypesModal *dobject = [[PopularHypesModal alloc]init];
dobject.dealsID = dealId;
dobject.dealDescription = dealdesc;
dobject.dealcaption = [dealcaption objectAtIndex:j];
dobject.dealsUrl = [dealUrl objectAtIndex:j];
dobject.dealsMessage = dealMessage;
[self.items addObject:dobject];
[dobject release];
}
}
else
{
//[dealUrl enumerateObjectsUsingBlock:^(id obj,NSUInteger idx,BOOL *stop)
for(int j=0;j<[dealUrl count];j++)
{
PopularHypesModal *dobject=[[PopularHypesModal alloc]init];
dobject.dealsID = dealId;
dobject.dealDescription = dealdesc;
dobject.dealsMessage = dealMessage;
if([dealcaption count]>0)
{
dobject.dealcaption =[dealcaption objectAtIndex:0];
}
dobject.dealsUrl=[dealUrl objectAtIndex:j];
[self.items addObject:dobject];
[dobject release];
}
// ];
}
}
//];
carousel.dataSource = self;
carousel.delegate = self;
}onFailure:^(NSError *error) {
NSLog(#"Error fetching: %#", error);
popularHypes = YES;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Server Problem" message:#"Sorry, There is some Error with server,Please try after some time" delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
[alert show];
[alert release];
ij++;
}];//1st
[dealDict retain];
}
The button I have added in xib, How can I overcome this?
Running on a background thread shouldn't give you any issues, unless you try to update a UI element from that same background thread. Be sure to forward any UI-related activities to the main thread. For example:
- (void)viewWillAppear:(BOOL)animated {
[self performSelectorInBackground:#selector(refreshTableView)];
[super viewWillAppear:animated];
}
- (void)refreshTableView {
// YourCode
[self.tableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:YES];
}
hope it's helpful :)
Please try this NSThread method
[NSThread detachNewThreadSelector:#selector(RunMethodEvenWhenMinimized) toTarget:self withObject:dict];

Parsing RSS feed - retrieve images, urls?

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.

read and write using NSKeyedArchiver, ios

Below is a class to read and write data using nsarchive
Data.m
-(id)init {
self = [super init];
if(self) {
arr = [[NSMutableArray alloc] init];
}
return self;
}
-(NSString *)getPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath;
if ([paths count] > 0)
documentPath = [paths objectAtIndex:0];
NSString *draftDataPath = [documentPath stringByAppendingPathComponent:#"draftData.dat"];
return draftDataPath;
}
-(void)saveDataToDisk {
NSString *path = [self getPath];
[NSKeyedArchiver archiveRootObject:arr toFile:path];
}
-(void)loadDataFromDisk {
NSString *path = [self getPath];
self.arr = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
}
At later on, I am adding some objects into arr by doing
CustomerClass.m
- (void) viewDidLoad {
Data *data = [[Data alloc] init];
[data.arr addObject:myObject1]
[data.arr addObject:myObject2]
[data.arr addObject:myObject3]
[data saveDataToDisk];
}
At DisplayData.m, I want to check data.arr by
- (void) viewDidLoad {
Data *data = [[Data alloc] init];
[data loadDataFromDisk];
NSLog(#"length of array is %d",[data.arr count]);
}
On the console, I am getting
length of array is 1
I thought it should be 3 after all.
Please point out what I have just made a mistake in the middle of work if you have any clues about it.
So, I suspect that your "myObjects" are not NSCoding compliant. I just did this:
NSMutableArray *arr = [NSMutableArray arrayWithCapacity:3];
[arr addObject:#"Hello"];
[arr addObject:#" "];
[arr addObject:#"World"];
BOOL ret = [NSKeyedArchiver archiveRootObject:arr toFile:[self getPath]];
NSArray *arr2 = [NSKeyedUnarchiver unarchiveObjectWithFile:[self getPath]];
NSLog(#"count = %d", [arr2 count]);
And the results was "count = 3"
I feel like there's too much code here to do what you're looking for. I think all you need is:
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:dataClass] forKey:NSUserDefaultString];
[[NSUserDefaults standardUserDefaults] synchronize];
to save it.
And:
NSData *someData = [[NSUserDefaults standardUserDefaults] objectForKey:NSUserDefaultString];
if (settingsData != nil)
{
dataClass = [NSKeyedUnarchiver unarchiveObjectWithData:settingsData];
}
to retrieve it.

My app crashes with "Program received EXC_BAD_ACCESS" error iphone

When my app launches from BACKGROUND , I am running a new thread to get AddresssBook data using notification center. Here is my code which shows how I call the method
-(void)appLaunchedFromBackground:(NSNotification *) notification {
// NSThread *backgroundThread; is my ivar
backgroundThread = [[NSThread alloc]initWithTarget:self selector:#selector(getUpdatedAddressBookData) object:nil];
[backgroundThread start];
}
-(void)getUpdatedAddressBookData {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
AddressBook *addBook = [[AddressBook alloc]init];
[addBook fetchAddressBookDataInBackground];
[addBook release];
[pool drain];
}
Here is my code for fetchAddressBookDataInBackground method
-(void)fetchAddressBookDataInBackground {
if (self.tempArray == nil) {
NSMutableArray *temp = [[NSMutableArray alloc]init];
self.tempArray = temp;
[temp release];
}
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *tempPeople = [[NSArray alloc]init];
tempPeople = (NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
APP_DELGATE.people = [NSArray arrayWithArray:tempPeople];
int peoCount = [APP_DELGATE.people count];
for (int i=0; i<peoCount; i++) {
ABRecordRef record = [APP_DELGATE.people objectAtIndex:i];
NSNumber *recordId = [NSNumber numberWithInteger:ABRecordGetRecordID(record)];
// Get fname, lname, company
NSString *fnm = (NSString *)ABRecordCopyValue(record, kABPersonFirstNameProperty) ;
NSString *lnm = (NSString *)ABRecordCopyValue(record, kABPersonLastNameProperty) ;
NSString *comp = (NSString*)ABRecordCopyValue(record,kABPersonOrganizationProperty);
// Get Ph no
ABMultiValueRef phoneNumberProperty = ABRecordCopyValue(record, kABPersonPhoneProperty);
NSArray *tempPhNos = (NSArray*)ABMultiValueCopyArrayOfAllValues(phoneNumberProperty);
NSArray* phoneNumbers = [self getPhoneNoWithoutSymbols:tempPhNos];
NSString *strPhoneNos = [self getStringRepresentaionFromArray:phoneNumbers];
// Get emails
ABMultiValueRef emailProperty = ABRecordCopyValue(record, kABPersonEmailProperty);
NSArray* emails = (NSArray*)ABMultiValueCopyArrayOfAllValues(emailProperty);
NSString *strEmails = [self getStringRepresentaionFromArray:emails];
// Get URL
ABMultiValueRef urlProperty = ABRecordCopyValue(record, kABPersonURLProperty);
NSArray* urls = (NSArray*)ABMultiValueCopyArrayOfAllValues(urlProperty);
NSString *strURLs = [self getStringRepresentaionFromArray:urls];
// Get Address
ABMultiValueRef address=ABRecordCopyValue(record, kABPersonAddressProperty);
CFDictionaryRef dic=nil;
NSMutableArray *addressArray = [[NSMutableArray alloc]init];
for (int index=0; index<ABMultiValueGetCount(address); index++) {
dic=ABMultiValueCopyValueAtIndex(address, index);
NSString* labelName=(NSString*)ABMultiValueCopyLabelAtIndex(address, index);
if (labelName) {
NSString *street =(NSString*) CFDictionaryGetValue(dic, kABPersonAddressStreetKey);
NSString *city= (NSString*)CFDictionaryGetValue(dic, kABPersonAddressCityKey) ;
NSString *state= CFDictionaryGetValue(dic, kABPersonAddressStateKey);
NSString *country=CFDictionaryGetValue(dic, kABPersonAddressCountryKey);
NSString *zipcode=CFDictionaryGetValue(dic, kABPersonAddressZIPKey);
NSString *addressDetails=#"";
if (street) {
addressDetails=[NSString stringWithFormat:#"%# ",street];
}
if (city) {
addressDetails=[NSString stringWithFormat:#"%# %# ",addressDetails,city];
}
if (state) {
addressDetails=[NSString stringWithFormat:#"%# %# ",addressDetails,state];
}
if (country) {
addressDetails=[NSString stringWithFormat:#"%# %# ",addressDetails,country];
}
if (zipcode) {
addressDetails=[NSString stringWithFormat:#"%# %# ",addressDetails,zipcode];
}
[addressArray addObject:addressDetails];
}
[labelName release];
CFRelease(dic);
}
NSString *strAddress = [self getStringRepresentaionFromArray:addressArray];
// Get Notes
NSString *noteString=(NSString *)ABRecordCopyValue(record, kABPersonNoteProperty);
// Get Birthdate
NSDate *birthDate=(NSDate*)ABRecordCopyValue(record, kABPersonBirthdayProperty) ;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMMM dd yyyy"];
NSString *birthdateString = [formatter stringFromDate:birthDate];
[formatter release];
// Get user image
UIImage *image = nil;
if( ABPersonHasImageData( record ) ) {
NSData *imageData = (NSData*)ABPersonCopyImageData(record);
image = [UIImage imageWithData:imageData];
[imageData release];
}
NSString *fullName = [NSString stringWithFormat:#"%# %#",fnm,lnm];
// Create User object & add it to array
User *user = [[User alloc]initUserWithUniqID:recordId.intValue FirstName:fnm lastName:lnm compositeName:fullName company:comp phoneNumbers:strPhoneNos emails:strEmails urls:strURLs address:strAddress notes:noteString dob:birthdateString userImage:image];
[self.tempArray addObject:user];
CFRelease(phoneNumberProperty);
[tempPhNos release];
CFRelease(emailProperty);
[emails release];
CFRelease(urlProperty);
[urls release];
CFRelease(address);
[addressArray release];
[birthDate release];
[comp release];
[noteString release];
[lnm release];
[fnm release];
[user release];
}
[tempPeople release];
CFRelease(addressBook);
addressBook = nil;
self.tempArray = [NSMutableArray arrayWithArray:[self.tempArray sortedArrayUsingSelector:#selector(compare:)]];
APP_DELGATE.allUsersArray = self.tempArray;
NSDictionary *dic = [NSDictionary dictionaryWithObject:self.tempArray forKey:BATCH_DONE_KEY];
[[NSNotificationCenter defaultCenter] postNotificationName:BACKGROUND_WORK_DONE_NOTIFICATION object:self userInfo:dic];
}
-(NSMutableArray*)getPhoneNoWithoutSymbols:(NSArray*)array {
if (self.phNoArray == nil) {
NSMutableArray *temp = [[NSMutableArray alloc]init];
self.phNoArray = temp;
[temp release];
}
[self.phNoArray removeAllObjects];
for (NSString *str in array) {
[self.phNoArray addObject:[self getPhNo:str]];
}
return self.phNoArray;
}
-(NSString*)getPhNo:(NSString*)str {
NSString *str0 = [str stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *str1 = [str0 stringByReplacingOccurrencesOfString:#"(" withString:#""];
NSString *str2 = [str1 stringByReplacingOccurrencesOfString:#")" withString:#""];
NSString *str3 = [str2 stringByReplacingOccurrencesOfString:#"-" withString:#""];
return str3;
}
-(NSString*)getStringRepresentaionFromArray:(NSArray*)array {
return [array componentsJoinedByString:DELIMITER_SYMBOL];
}
But my app crashes with "Program received EXC_BAD_ACCESS" error at any line where I am using "ABRecordCopyValue" function . What I am missing? I am not getting whats wrong in my code?
I tried setting NSZombieEnabled = YES , but its not showing any message. Just saying "Program received EXC_BAD_ACCESS" at any line using ABRecordCopyValue function & in console I see (gdb) thats it.
Any knid of help is highly appreciated. Thanks.

Memory Leak related

i am working on a fishing app these days and i am getting a memory leak problem
-(void)requestFinished:(ASIFormDataRequest *) request {
if(hud != nil){
[hud show:NO];
[hud release];
hud = nil;
}
isLoading = NO;
self.responseText = [request responseString];
[self parseXml]; //I am getting leak here
if ( [self.responseText hasPrefix:#"<result>"]) {
UIAlertView *info = [[[UIAlertView alloc] initWithTitle:#" " message:#"Limited Internet access, please find a stronger signal in the area" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil]autorelease];
[info show];
}
if (!isRefreshButtonClicked) {
[UIAccelerometer sharedAccelerometer].delegate = self;
[NSThread detachNewThreadSelector:#selector(parseXml) toTarget:self withObject:nil];
} }
This is my function...
-(void) parseXml
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
_fishes = [[fishes parseXml:self.responseText] retain];
[self performSelectorOnMainThread:#selector(parseXmlDone) withObject:nil waitUntilDone:YES];
[pool release];
Here _fishes is an array which is getting a value from a array return type function.....and here is that function...
+(NSMutableArray *)parseXml:(NSString *)xmlString {
//xmlString = [xmlString stringByReplacingOccurrencesOfString:#"&" withString:#""];
const char *cString = [xmlString UTF8String];
NSMutableArray *fishes = [NSMutableArray array];
NSData *xmlData = [NSData dataWithBytes:cString length:strlen(cString)];
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc]initWithData:xmlData options:0 error:&error];
if (doc == nil) { return nil; }
//parseXml
NSArray *_fishes = [doc.rootElement elementsForName:#"fishery"];
for (GDataXMLElement *_fish in _fishes) {
NSMutableDictionary *fish = [NSMutableDictionary dictionary];
NSArray *ids = [_fish elementsForName:#"id"];
if ([ids count]>0) {
GDataXMLElement *firstId = (GDataXMLElement *)[ids objectAtIndex:0];
[fish setValue:firstId.stringValue forKey:#"id"];
} else continue;
NSArray *names = [_fish elementsForName:#"name"];
if ([names count]>0) {
GDataXMLElement *firstName = (GDataXMLElement *)[names objectAtIndex:0];
[fish setValue:firstName.stringValue forKey:#"name"];...........
........
else continue;
NSArray *distances = [_fish elementsForName:#"distance"];
if ([distances count]>0) {
GDataXMLElement *distance = (GDataXMLElement *)[distances objectAtIndex:0];
[fish setValue:distance.stringValue forKey:#"distance"];
}else continue;
[fishes addObject:fish];
}
[doc release];
return fishes;
}
#end
I hope u guys will understand my problem...thanx
In -parseXml,
_fishes = [[fishes parseXml:self.responseText] retain];
will leak any previous object _fishes was pointing to in case -parseXml is sent more than once. You could use a retain property instead of an instance variable, or a setter method that releases the previous object, or release the previous object before assigning a new (retained) object to _fishes.