Why application shows low memory warning during heap shot analysis? - iphone

I am developing one application in which recurring transactions are inserted in database.while i am doing heap shot analysis it shows low memory warning while inserting data.its inserting 1200 records approximately.The code for insertion is as below.
-(void)generateReccuringEntry:(int)tranId withAllDate:(BOOL)isAll
{
NSMutableArray *arrDates = [[NSMutableArray alloc] init] ;
NSArray *arr = [[_dicSaveData valueForKey:#"tran_repeatd"] componentsSeparatedByString:#" "];
int day;
if ([self getDayWithDayMonth:[arr objectAtIndex:1]] == 0) {
day = [self getDay:[arr objectAtIndex:1]];
}
else{
day = 1;
}
NSDate *startDate = [_dicSaveData valueForKey:#"tran_date"];
NSString *strEndDate = [NSString stringWithFormat:#"%#",[_dicSaveData valueForKey:#"tran_enddate"]];
NSDate *endDate = nil;
strEndDate = [strEndDate stringByReplacingOccurrencesOfString:#"(null)" withString:#""];
if (![strEndDate stringIsEmpty]) {
endDate = [_dicSaveData valueForKey:#"tran_enddate"];
}
else {
//if end date not selected
endDate = [[startDate dateByAddingYear:1]lastOfYearDate];
}
//get start recurring day
NSString *strDay = [[arr lastObject] stringByReplacingOccurrencesOfString:#"()" withString:#""];
//check start recuring day selected or not
if ([strDay hasPrefix:#"("] && [strDay hasSuffix:#")"])
{
startDate = [self getStartDay:[arr lastObject] withStartingDate:startDate];
if ([startDate compare:endDate]==NSOrderedDescending || [startDate compare:endDate]==NSOrderedSame)
{
SafeRelease(arrDates);
return;
}
if (isAll)
{
NSError *error = nil;
NSString *strQuery = [NSString stringWithFormat:#"insert into recuring values (NULL,%i,%#,%#,'%#',%#,'%#','','%#','%#',%i,1,'%#',0)",tranId,[_dicSaveData valueForKey:#"cat_id"],[_dicSaveData valueForKey:#"subcat_id"],_txtDesc.text,_txtAmount.text,sDate,[_dicSaveData valueForKey:#"tran_repeatd"],eDate,_flagForever,[_dicSaveData valueForKey:#"categoryText"]];
strQuery = [strQuery stringByReplacingOccurrencesOfString:#"(null)" withString:#""];
[NSNumber requestWithSynchronousExcuteQuery:strQuery withReturnningError:&error];
if (error) {
[AppDelegate showAlert:[error description] withTitle:#"Error!"];
}
}
else{
NSDate *currentDate = [[NSDate date] getDateWithDeviceTimeZone];
if ([startDate compare:currentDate]== NSOrderedDescending)
{
NSError *error = nil;
NSString *strQuery = [NSString stringWithFormat:#"insert into recuring values (NULL,%i,%#,%#,'%#',%#,'%#','','%#','%#',%i,1,'%#',0)",tranId,[_dicSaveData valueForKey:#"cat_id"],[_dicSaveData valueForKey:#"subcat_id"],_txtDesc.text,_txtAmount.text,sDate,[_dicSaveData valueForKey:#"tran_repeatd"],eDate,_flagForever,[_dicSaveData valueForKey:#"categoryText"]];
strQuery = [strQuery stringByReplacingOccurrencesOfString:#"(null)" withString:#""];
[NSNumber requestWithSynchronousExcuteQuery:strQuery withReturnningError:&error];
if (error) {
[AppDelegate showAlert:[error description] withTitle:#"Error!"];
}
}
}
}
int index = 2;
if (day == 1) {
index = 1;
}
do {
if ([[arr objectAtIndex:index] isEqualToString:#"Week"])
{
startDate = [startDate dateByAddingWeek:day];
}
else if([[arr objectAtIndex:index] isEqualToString:#"Month"])
{
startDate = [startDate dateByAddingMonth:day];
}
else
{
startDate = [startDate dateByAddingDays:day];
}
if (isAll)
{
NSError *error = nil;
NSString *strQuery = [NSString stringWithFormat:#"insert into recuring values (NULL,%i,%#,%#,'%#',%#,'%#','','%#','%#',%i,1,'%#',0)",tranId,[_dicSaveData valueForKey:#"cat_id"],[_dicSaveData valueForKey:#"subcat_id"],_txtDesc.text,_txtAmount.text,sDate,[_dicSaveData valueForKey:#"tran_repeatd"],eDate,_flagForever,[_dicSaveData valueForKey:#"categoryText"]];
strQuery = [strQuery stringByReplacingOccurrencesOfString:#"(null)" withString:#""];
[NSNumber requestWithSynchronousExcuteQuery:strQuery withReturnningError:&error];
if (error) {
[AppDelegate showAlert:[error description] withTitle:#"Error!"];
}
}
//add recuring for only for future dates
else
{
NSDate *currentDate = [[NSDate date] getDateWithDeviceTimeZone];
if ([startDate compare:currentDate]== NSOrderedDescending)
{
NSError *error = nil;
NSString *strQuery = [NSString stringWithFormat:#"insert into recuring values (NULL,%i,%#,%#,'%#',%#,'%#','','%#','%#',%i,1,'%#',0)",tranId,[_dicSaveData valueForKey:#"cat_id"],[_dicSaveData valueForKey:#"subcat_id"],_txtDesc.text,_txtAmount.text,sDate,[_dicSaveData valueForKey:#"tran_repeatd"],eDate,_flagForever,[_dicSaveData valueForKey:#"categoryText"]];
strQuery = [strQuery stringByReplacingOccurrencesOfString:#"(null)" withString:#""];
[NSNumber requestWithSynchronousExcuteQuery:strQuery withReturnningError:&error];
if (error) {
[AppDelegate showAlert:[error description] withTitle:#"Error!"];
}
}
}
} while ([startDate compare:endDate]==NSOrderedAscending );
SafeRelease(arrDates);
}
can anyone tell that what is the problem with this code.so that its consuming so much memory?
Update:I have converted app to ARC.but it still shows memory warning.

Highly recommend you convert (if you can) to ARC. The compiler is far more capable of inserting the most efficient retains/releases for you. Would also completely remove any need for anything like SafeRelease.

Related

Information not being received from server?

Okay, my problem is very simple. Below is my code that is receiving prices from an API, in my code I want the today current price to be displayed, yesterdays price, and the change in percent from yesterday to today. Unfortunately, only the current price is showing properly, but the yesterday and the percent change just show N/A.
Any help is appreciated!
if (refreshing) return;
refreshing = YES;
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = YES;
//self.priceLabel.text = #"Loading...";
//self.yesterdayLabel.text = #"Loading...";
//self.changeLabel.text = #"Loading...";
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"https://coinbase.com/api/v1/prices/spot_rate"]] queue:[NSOperationQueue mainQueue] completionHandler:^ (NSURLResponse *req, NSData *recv, NSError *err) {
if (err) {
// report
[self setCurrentPrice:#"N/A"];
refreshing = NO;
return;
}
NSError *newError = nil;
NSDictionary *serial = [NSJSONSerialization JSONObjectWithData:recv options:0 error:&newError];
if (newError) {
// report
[self setCurrentPrice:#"N/A"];
refreshing = NO;
return;
}
NSString *amount = [serial objectForKey:#"amount"];
NSString *price = [NSString stringWithFormat:#"%# %#", amount, [serial objectForKey:#"currency"]];
[self setCurrentPrice:[NSString stringWithFormat:#"%#", price]];
// maybe setup a better method.
float diff = [yesterdaysPrice floatValue];
if (diff == 0.0)
self.differenceInPrices = #"N/A";
else {
float amt = [amount floatValue];
float percentChange = amt/diff;
if ((diff == 0) || (amt == diff))
percentChange = 0.00;
percentChange *= 100.00;
self.differenceInPrices = [NSString stringWithFormat:#"%f%%", percentChange];
}
NSMutableDictionary *saveState = [[[NSUserDefaults standardUserDefaults] objectForKey:#"save"] mutableCopy];
[saveState setObject:price forKey:#"price"];
[saveState setObject:yesterdaysPrice forKey:#"lastCheckedPrice"];
NSDateComponents *compon = [[NSCalendar currentCalendar] components:(NSUndefinedDateComponent) fromDate:[NSDate date]];
[saveState setObject:[NSString stringWithFormat:#"%ld", (usingYesterdaysPrices ? [[saveState objectForKey:#"day"] intValue] : [compon day])] forKey:#"day"];
[[NSUserDefaults standardUserDefaults] setObject:saveState forKey:#"save"];
[[NSUserDefaults standardUserDefaults] synchronize];
self.priceLabel.text =self.currentPrice;
self.yesterdayLabel.text = [NSString stringWithFormat:#"%#", yesterdaysPrice];
self.changeLabel.text = differenceInPrices;
app.networkActivityIndicatorVisible = NO;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM/dd/yyyy"];
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:#"h:mm:ss aa"];
NSDate *now = [[NSDate alloc] init];
NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];
lstUpdate.text = [NSString stringWithFormat:#"Updated: %# at %#", theDate, theTime];
refreshing = NO;
}];
I also have this code in my viewDidLoad,
[super viewDidLoad];
refreshing = NO;
NSDictionary *save = [[NSUserDefaults standardUserDefaults] objectForKey:#"save"];
if (save) {
int timeStamp = [[save objectForKey:#"day"] intValue];
NSDateComponents *compon = [[NSCalendar currentCalendar] components:(NSUndefinedDateComponent) fromDate:[NSDate date]];
if ([compon day] != timeStamp) {
usingYesterdaysPrices = YES;
yesterdaysPrice = [save objectForKey:#"lastCheckedPrice"];
if (!yesterdaysPrice) {
yesterdaysPrice = #"N/A";
}
}
}
else {
yesterdaysPrice = #"N/A";
}
self.differenceInPrices = #"N/A";
[self sendNewRequest:nil];
[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:#selector(sendNewRequest:) userInfo:Nil repeats:YES];

Some strange error occurs when manipulating events in the calendar of iOS device

I added some events to the calendar and save their eventIdentifier to file. When i want to remove all my events i read the eventIdentifier from that file to an array and remove each event with its event id. Here is the code to add event to calendar and save their event id to file:
- (void) addEventToCalendar: (id)object
{
#autoreleasepool {
int i = 0;
NSString *string_to_file = #"";
eventStore=[[EKEventStore alloc] init];
for(Schedule *sche in scheduleArray){
EKEvent *addEvent=[EKEvent eventWithEventStore:eventStore];
addEvent.title=sche.course_Name;
addEvent.startDate = [self stringToDate:sche.from_Date];
addEvent.endDate = [self stringToDate:sche.thru_Date];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[addEvent setCalendar:[eventStore defaultCalendarForNewEvents]];
NSDate *date_alarm = [addEvent.startDate dateByAddingTimeInterval:-(10*60)];
addEvent.alarms=[NSArray arrayWithObject:[EKAlarm alarmWithAbsoluteDate:date_alarm]];
NSError *err;
// do save event to calendar
[eventStore saveEvent:addEvent span:EKSpanThisEvent error:&err];
if (err == nil) {
NSString* str = [[NSString alloc] initWithFormat:#"%#", addEvent.eventIdentifier];
string_to_file = [string_to_file stringByAppendingString:str];
string_to_file = [string_to_file stringByAppendingString:#"\n"];
NSLog(#"String %d: %#",i, str);
}
else {
NSLog(#"Error %#",err);
}
i++;
}
// create file to save
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
inFile = [NSFileHandle fileHandleForWritingAtPath: filePath];
NSData *data = [string_to_file dataUsingEncoding:NSUTF16StringEncoding];
[inFile writeData:data];
}
}
And the code below to remove all events i have added to calendar
- (void) deleteEventInCalender {
filemgr = [NSFileManager defaultManager];
NSString *filePath = [self getFilePath:#"saveeventid.txt"];
NSFileHandle *inFile;
inFile = [NSFileHandle fileHandleForReadingAtPath:filePath];
NSData *dataFile;
dataFile = [inFile readDataToEndOfFile];
NSString *tmp = #"";
NSString *temp = #"";
tmp = [NSString stringWithCharacters:[dataFile bytes] length:[dataFile length]/sizeof(unichar)];
if(![tmp isEqualToString:#""]){
tmp = [tmp substringFromIndex:1];
event_idArray = [[NSMutableArray alloc] init];
int j = 0;
while (![tmp isEqualToString:#""]){
int index_find_string = [tmp rangeOfString:#"\n"].location;
temp = [tmp substringWithRange:NSMakeRange(0, index_find_string)];
[event_idArray addObject:temp];
tmp = [tmp substringFromIndex:index_find_string + 1];
}
EKEventStore* store = [[EKEventStore alloc] init];
j = 0;
for(NSString *eventid in event_idArray){
EKEvent* event2 = [store eventWithIdentifier:eventid];
if (event2 != nil) {
NSLog(#"log: %d log id: %#", j, eventid);
NSError* error = nil;
// remove event
[store removeEvent:event2 span:EKSpanThisEvent error:&error];
}
j++;
}
[filemgr removeItemAtPath:filePath error:nil];
}
}
All codes above work well when i test on the iOS simulator with calendar.sqlitedb. But it makes some strange errors when i run on iPad device 5.0. That is sometime the calendar not remove event or when all events has been remove then after some minutes all events appear again... I don't understand, i don't know why and i very confuse. Does anyone has the same issue with me? Please share your solution!
Added another question: where the calendar database stored in the iOS 5.0 device.

Add calendar on iCloud on iOS

i'm trying to add a calendar to the iCloud EKSource, i'm trying to find the iCloud calendar in this way:
EKSource *theSource = nil;
for (EKSource *source in eventStore.sources) {
if (source.sourceType == EKSourceTypeCalDAV && [source.title isEqualToString:#"iCloud"]) {
theSource = source;
break;
}
}
but don't find my any EKSource, how i can add a calendar on icloud and see how many calendar are in icloud?
Perhaps something like this will help you..
- (void)saveEventToiCloud {
EKEventStore *eventDB = [[EKEventStore alloc] init];
NSArray *calender = [[eventDB calendars] retain];
NSString * typeString = #"";
EKCalendar *iCloud;
for (EKCalendar *thisCalendar in calenders)
{
EKCalendarType type = thisCalendar.type;
if (type == EKCalendarTypeCalDAV)
{
NSString *calName=[NSString stringWithFormat:#"%#", thisCalendar.title];
NSRange range = [calName rangeOfString:#"iCloud"]; //Couldn't find better way, if there is, then tell me too. :)
if(range.length!=0)
{
//icloud
iCloud = thisCalendar;
break;
}
else
{
//any other email account
}
}
}
if(iCloud){
NSError *error = nil;
EKEvent *thisEvent = [[EKEvent eventWithEventStore:eventDB] retain];
thisEvent.title = #"Title";
thisEvent.startDate = [NSDate date];
thisEvent.endDate = [NSDate date];
thisEvent.calendar = iCloud ;
BOOL saved = [eventDB saveEvent:thisEvent span:EKSpanThisEvent error:&error];
NSLog(#"Saved calendar event = %#\n", (saved ? #"YES" : #"NO"));
[thisEvent release];
thisEvent=nil;
}
[events release];
[eventDB release];
}

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.

NSString memory leak

I am getting a memory leak in a method that builds a email message string from a NSManagedObject. The string is created with NSString convenience methods, and so should be autoreleased. What am I missing? Code below... Instruments is flagging the final occurance of buildString near the bottom of the method (see comment in code):
-(void)buildEmailMessage {
//check for presence of lat and lon data
BOOL hasStartLatLon = NO;
BOOL hasEndLanLon = NO;
NSString *startLat;
NSString *startLong;
NSString *endLat;
NSString *endLong;
NSString *mapURL;
NSString *finalMapURL;
if( [managedObject valueForKey:#"startLat"] > 0 ){
hasStartLatLon = YES;
startLat = [self formatLatLon:[managedObject valueForKey:#"startLat"]];
startLong= [self formatLatLon:[managedObject valueForKey:#"startLong"]];
}
if( [managedObject valueForKey:#"endLat"] > 0 ) {
hasEndLanLon = YES;
endLat = [self formatLatLon:[managedObject valueForKey:#"endLat"]];
endLong= [self formatLatLon:[managedObject valueForKey:#"endLong"]];
}
// Build strings from managedObject
// Start with the trip info already validated
NSString *tripName = [managedObject valueForKey:#"tripName"];
NSString *intro = [NSString stringWithString:#"Please contact the approriate authorities and provide them with the enclosed information if our party does not return withing 12 hours of the return date shown below. Thanks."];
id vStartDate = [managedObject valueForKey:#"startDate"];
NSString *startDate = [NSString stringWithFormat:#"Start Date: %#", [vStartDate managedObjectValueDisplay]];
id vEndDate = [managedObject valueForKey:#"endDate"];
NSString *endDate = [NSString stringWithFormat:#"End Date: %#", [vEndDate managedObjectValueDisplay]];
NSString *startFrom = [NSString stringWithFormat:#"Departing from:%#", [managedObject valueForKey:#"startFrom"]];
if( hasStartLatLon ){
startFrom = [startFrom stringByAppendingString:#""];
startFrom = [startFrom stringByAppendingString:[self getLatLon:#"start"]];
}
startFrom = [startFrom stringByAppendingString:#""];
NSString *endAt = [NSString stringWithFormat:#"Returning to:%#", [managedObject valueForKey:#"endAt"]];
if( hasStartLatLon ){
endAt = [endAt stringByAppendingString:#""];
endAt = [endAt stringByAppendingString:[self getLatLon:#"end"]];
}
endAt = [startFrom stringByAppendingString:#""];
// Add a link to Google Maps if there is geodata
if (hasStartLatLon || hasEndLanLon) {
if (hasStartLatLon) {
mapURL = [NSString stringWithFormat:#"http://maps.google.com/?q=%#,%#+(%#)&ll=%#,%#&z=14&t=p", startLat, startLong, [managedObject valueForKey:#"startFrom"], startLat, startLong];
} else {
mapURL = [NSString stringWithFormat:#"http://maps.google.com/?q=%#,%#+(%#)&ll=%#,%#&z=14&t=p", endLat, endLong, [managedObject valueForKey:#"endAt"], endLat, endLong];
}
NSString* escapedUrlString =[mapURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"escaped map url = %#", escapedUrlString);
finalMapURL = [NSString stringWithFormat:#"Link to Google Map:%#", escapedUrlString];
}
NSString *routeInfo = [NSString stringWithFormat:#"Route Information:%# ", [managedObject valueForKey:#"routeInfo"]];
// Check for vehicle info
BOOL hasVehicleMakeAndModel = NO;
BOOL hasVehicleLicenseNumber = NO;
BOOL hasVehicleState = NO;
NSString *vehicleMakeAndModel = [managedObject valueForKey:#"vehicleMakeAndModel"];
NSString *vehicleLicenseNumber = [managedObject valueForKey:#"vehicleLicenseNumber"];
NSString *vehicleState = [managedObject valueForKey:#"vehicleState"];
if ( vehicleMakeAndModel.length > 0 ) {
hasVehicleMakeAndModel = YES;
}
if ( vehicleLicenseNumber.length > 0 ) {
hasVehicleLicenseNumber = YES;
}
if ( vehicleState.length > 0 ) {
hasVehicleState = YES;
}
//Build the vehicle string
NSString *vehicleString;
if (hasVehicleMakeAndModel || hasVehicleLicenseNumber || hasVehicleState) {
vehicleString = [NSString stringWithString:#"Vehicle Information:"];
}
if (hasVehicleMakeAndModel) {
vehicleString = [vehicleString stringByAppendingString:#"Make/Model: "];
vehicleString = [vehicleString stringByAppendingString:vehicleMakeAndModel];
vehicleString = [vehicleString stringByAppendingString:#""];
}
if (hasVehicleLicenseNumber) {
vehicleString = [vehicleString stringByAppendingString:#"License #: "];
vehicleString = [vehicleString stringByAppendingString:vehicleLicenseNumber];
vehicleString = [vehicleString stringByAppendingString:#""];
}
if (hasVehicleState) {
vehicleString = [vehicleString stringByAppendingString:#"State: "];
vehicleString = [vehicleString stringByAppendingString:vehicleState];
}
// Get the NSSet of party members from the managedObject
// and build the party members/emergency contact info
NSSet *membersSet = [managedObject valueForKey:#"members"];
NSString *membersString;
if ( [membersSet count] > 0) {
membersString = #"Party Members:";
NSArray *membersArray = [NSArray arrayByOrderingSet:membersSet byKey:#"lastName" ascending:YES];
for (NSManagedObject *oneObject in membersArray) {
BOOL hasFirstName = NO;
BOOL hasLastName = NO;
BOOL hasAge = NO;
BOOL hasContactName = NO;
BOOL hasContactNumber = NO;
NSString *memberFirstName = [oneObject valueForKey:#"firstName"];
NSString *memberLastName = [oneObject valueForKey:#"lastName"];
NSNumber *memberAgeNum = [oneObject valueForKey:#"age"];
NSString *memberAgeString;
if (memberAgeNum > 0) {
memberAgeString = [NSString stringWithFormat:#"%d", [memberAgeNum intValue]];
} else {
memberAgeString = [NSString stringWithString:#""];
}
NSString *contactName = [oneObject valueForKey:#"contactName"];
NSString *contactNumber = [oneObject valueForKey:#"contactNumber"];
if ( [memberFirstName length] > 0) {
hasFirstName = YES;
}
if ( [memberLastName length] > 0) {
hasLastName = YES;
}
if ( [memberAgeString length] > 0) {
hasAge = YES;
}
if ( [contactName length] > 0) {
hasContactName = YES;
}
if ( [contactNumber length] > 0) {
hasContactNumber = YES;
}
NSString *oneMemberString = [NSString stringWithString:#""];
if (hasFirstName) {
oneMemberString = [oneMemberString stringByAppendingFormat:#"%# ", memberFirstName];
}
if (hasLastName) {
oneMemberString = [oneMemberString stringByAppendingString:memberLastName];
}
if (hasAge) {
oneMemberString = [oneMemberString stringByAppendingFormat:#", %#", memberAgeString];
}
if (hasContactName) {
oneMemberString = [oneMemberString stringByAppendingFormat:#"Emergency Contact:%#", contactName];
}
if (hasContactNumber) {
oneMemberString = [oneMemberString stringByAppendingFormat:#"Phone: %#", contactNumber];
}
membersString = [membersString stringByAppendingString:oneMemberString];
}
}
NSString *buildString = [NSString stringWithFormat:#"Trip Plan for:%#", tripName];
buildString = [buildString stringByAppendingString: intro];
buildString = [buildString stringByAppendingString: startDate];
buildString = [buildString stringByAppendingString: endDate];
buildString = [buildString stringByAppendingString: startFrom];
buildString = [buildString stringByAppendingString: endAt];
if (hasStartLatLon || hasEndLanLon) buildString = [buildString stringByAppendingString: finalMapURL];
buildString = [buildString stringByAppendingString: routeInfo];
// Append the vehicle string if any vehicle data is present
if (hasVehicleMakeAndModel || hasVehicleLicenseNumber || hasVehicleState) {
buildString = [buildString stringByAppendingString: vehicleString];
}
// Append the members string if any members data is present
// **MEMORY LEAK** flagged on the line enclosed by the if statement below
if ( [membersSet count] > 0) {
buildString = [buildString stringByAppendingString: membersString];
}
self.myEmailString = [NSString stringWithString:buildString];
}
-(NSString *)formatLatLon:(NSNumber *)value {
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setPositiveFormat:#"##0.00000"];
NSString *returnString = [formatter stringFromNumber:value];
[formatter release];
return returnString;
}
How is your myEmailString #property defined? With copy or retain? (You should use copy with NSString objects.) If so, and you're not doing a [myEmailString release] in dealloc, that might be the leak.