NSString memory leak - iphone

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.

Related

UIApplicationWillEnterForegroundNotification not called

Hi I am very new in Iphone Development. I have a question :
I am using UIApplicationDeligate in my Appdeligate class and in this class i use two methods
applicationDidEnterBackground and applicationdisEnterForeGround. then these method works fine , when my app goes in background or in comes in foreground then flow goes inside these method.
But in another UiViewController class i attach listener for UIApplicationdidEnterForegroundNotification and UiApplicationdidEnterBackgroundNotification.
now when my app goes in background then flow goes in background method but when my app comes in foreground then app flow never comes in foreground method.
code which i am using in AppDelegate Class :
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:timertimetobefired forKey:#"TimerTimeToFired"];
[defaults setValue:timerrecipename forKey:#"TimerRecipeName"];
[defaults setObject:storingbuttonstate forKey:#"TimerButtonState"];
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
timertimetobefired = [defaults objectForKey:#"TimerTimeToFired"];
timerrecipename = [defaults objectForKey:#"TimerRecipeName"];
storingbuttonstate = [defaults objectForKey:#"TimerButtonState"];
}
and code which i am using inside UiViewController class :
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(goBackground)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
[[NSNotificationCenter defaultCenter]
addObserver:#"forground"
selector:#selector(doMyLayoutStuff:)
name: UIApplicationWillEnterForegroundNotification
object:nil];
- (void) goBackground
{
if(timer != nil && [timer isValid])
{
[timer invalidate], timer = nil;
}
}
can anyone tell me what wrong with this code . Thanks in advance.
code inside doMylayoutStuff :
- (void)doMyLayoutStuff:(id)sender
{
fortimer=0;
appdelegate.imgRecipePhoto=nil;
recipeMakingTime=0;
arrForStepsReminder=[[NSMutableArray alloc]init];
[arrForStepsReminder removeAllObjects];
arrForSteps5=[[NSMutableArray alloc]init];
[arrForSteps5 removeAllObjects];
arrForButtonSelection=[[NSMutableArray alloc]init];
[arrForButtonSelection removeAllObjects];
[arrForSteps5 addObjectsFromArray:appdelegate.arrStepsandTime];
arrayforshowingdata = [[NSMutableArray alloc]initWithCapacity:arrForSteps5.count];
for (int i=0; i<[arrForSteps5 count]; i++)
{
//nitin tyagi. 6/08/2013.
// NSString *str12=[[arrForSteps5 objectAtIndex:i]objectForKey:#"RecipestepTime"];
// if (str12.length==0)
// {
// [arrForSteps5 removeObjectAtIndex:i];
// }
// else
// {
// }
NSString *timer1 = [[arrForSteps5 objectAtIndex:i]objectForKey:#"RecipeTimer1"];
NSString *timer2 = [[arrForSteps5 objectAtIndex:i]objectForKey:#"RecipeTimer2"];
NSString *timer3 = [[arrForSteps5 objectAtIndex:i]objectForKey:#"RecipeTimer3"];
NSString *timer4 = [[arrForSteps5 objectAtIndex:i]objectForKey:#"RecipeTimer4"];
timer1 = [timer1 stringByReplacingOccurrencesOfString:#" " withString:#""];
timer2 = [timer2 stringByReplacingOccurrencesOfString:#" " withString:#""];
timer3 = [timer3 stringByReplacingOccurrencesOfString:#" " withString:#""];
timer4 = [timer4 stringByReplacingOccurrencesOfString:#" " withString:#""];
NSMutableArray *finaltimerarray = [[NSMutableArray alloc]init];
int totalminute = 0;
int hours = 0;
if(([timer1 hasSuffix:#"mins"] || [timer1 hasSuffix:#"minute"] || [timer1 hasSuffix:#"min"]) || ([timer1 isEqualToString:#"0"]))
{
if(![timer1 isEqualToString:#"0"]){
NSRange range = [timer1 rangeOfString:#"min"];
NSString *minutes = [timer1 substringToIndex:range.location];
totalminute = totalminute + [minutes intValue];
NSNumber* xWrapped = [NSNumber numberWithInt:[minutes intValue]];
[finaltimerarray addObject:xWrapped];
}
else
{
[finaltimerarray addObject:[NSNumber numberWithInt:0]];
}
// NSLog(#"totalminute minute is = %#",totalminute);
}
else if(([timer1 hasSuffix:#"hours"] || [timer1 hasSuffix:#"hrs"] || [timer1 hasSuffix:#"hour"] || [timer1 hasSuffix:#"hr"]) )
{
if(![timer1 isEqualToString:#"0"]){
NSRange range = [timer1 rangeOfString:#"h"];
NSString *hours = [timer1 substringToIndex:range.location];
int minute = [hours intValue] * 60;
totalminute = totalminute + minute;
NSNumber* xWrapped = [NSNumber numberWithInt:minute];
[finaltimerarray addObject:xWrapped];
}
else
{
[finaltimerarray addObject:[NSNumber numberWithInt:0]];
}
// NSLog(#"timer1 minute is = %#",minutes);
}
if(([timer2 hasSuffix:#"mins"] || [timer2 hasSuffix:#"minute"] || [timer2 hasSuffix:#"min"]) || ([timer2 isEqualToString:#"0"]))
{
if(![timer2 isEqualToString:#"0"]){
NSRange range = [timer2 rangeOfString:#"min"];
NSString *minutes = [timer2 substringToIndex:range.location];
totalminute = totalminute + [minutes intValue];
NSNumber* xWrapped = [NSNumber numberWithInt:[minutes intValue]];
[finaltimerarray addObject:xWrapped];
}
else
{
[finaltimerarray addObject:[NSNumber numberWithInt:0]];
}
// NSLog(#"timer2 minute is = %#",minutes);
}
else if(([timer2 hasSuffix:#"hours"] || [timer2 hasSuffix:#"hrs"] || [timer2 hasSuffix:#"hour"] || [timer2 hasSuffix:#"hr"]) )
{
if(![timer2 isEqualToString:#"0"])
{
NSRange range = [timer2 rangeOfString:#"h"];
NSString *hours = [timer2 substringToIndex:range.location];
int minute = [hours intValue] * 60;
totalminute = totalminute + minute;
NSNumber* xWrapped = [NSNumber numberWithInt:minute];
[finaltimerarray addObject:xWrapped];
}
else
{
[finaltimerarray addObject:[NSNumber numberWithInt:0]];
}
// NSLog(#"timer1 minute is = %#",minutes);
}
if(([timer3 hasSuffix:#"mins"] || [timer3 hasSuffix:#"minute"] || [timer3 hasSuffix:#"min"]) || ([timer3 isEqualToString:#"0"]))
{
if( ![timer3 isEqualToString:#"0"])
{
NSRange range = [timer3 rangeOfString:#"min"];
NSString *minutes = [timer3 substringToIndex:range.location];
totalminute = totalminute + [minutes intValue];
NSNumber* xWrapped = [NSNumber numberWithInt:[minutes intValue]];
[finaltimerarray addObject:xWrapped];
}
else
{
[finaltimerarray addObject:[NSNumber numberWithInt:0]];
}
// NSLog(#"timer3 minute is = %#",minutes);
}
else if(([timer3 hasSuffix:#"hours"] || [timer3 hasSuffix:#"hrs"] || [timer3 hasSuffix:#"hour"] || [timer3 hasSuffix:#"hr"]) )
{
if(![timer3 isEqualToString:#"0"]){
NSRange range = [timer3 rangeOfString:#"h"];
NSString *hours = [timer3 substringToIndex:range.location];
int minute = [hours intValue] * 60;
totalminute = totalminute + minute;
NSNumber* xWrapped = [NSNumber numberWithInt:minute];
[finaltimerarray addObject:xWrapped];
}
else
{
[finaltimerarray addObject:[NSNumber numberWithInt:0]];
}
// NSLog(#"timer1 minute is = %#",minutes);
}
if(([timer4 hasSuffix:#"mins"] || [timer4 hasSuffix:#"minute"] || [timer4 hasSuffix:#"min"]) || ([timer4 isEqualToString:#"0"]))
{
if(![timer4 isEqualToString:#"0"])
{
NSRange range = [timer4 rangeOfString:#"min"];
NSString *minutes = [timer4 substringToIndex:range.location];
totalminute = totalminute + [minutes intValue];
NSNumber* xWrapped = [NSNumber numberWithInt:[minutes intValue]];
[finaltimerarray addObject:xWrapped];
}
else
{
[finaltimerarray addObject:[NSNumber numberWithInt:0]];
}
// NSLog(#"timer4 minute is = %#",minutes);
}
else if(([timer4 hasSuffix:#"hours"] || [timer4 hasSuffix:#"hrs"] || [timer4 hasSuffix:#"hour"] || [timer4 hasSuffix:#"hr"]) )
{
if(![timer4 isEqualToString:#"0"]){
NSRange range = [timer4 rangeOfString:#"h"];
NSString *hours = [timer4 substringToIndex:range.location];
int minute = [hours intValue] * 60;
totalminute = totalminute + minute;
NSNumber* xWrapped = [NSNumber numberWithInt:minute];
[finaltimerarray addObject:xWrapped];
}
else
{
[finaltimerarray addObject:[NSNumber numberWithInt:0]];
}
// NSLog(#"timer1 minute is = %#",minutes);
}
[arrayforshowingdata addObject:finaltimerarray];
[finaltimerarray release];
}
for (int i=0; i<[arrayforshowingdata count]; i++)
{
NSMutableArray *arraydata = [arrayforshowingdata objectAtIndex:i];
for (int j=0; j<[arraydata count]; j++)
{
[arrForStepsReminder addObject:#"0"];
}
[arrForButtonSelection addObject:#"M"];
}
lblDisplayTimer.text=#"00:00:00";
lblRecipeName.text=appdelegate.strRecipeName;
currentdate = [NSDate date];
NSDate *timetobefired = appdelegate.timertimetobefired;
timerrecipe = appdelegate.timerrecipename;
if(timerrecipe != nil && ([timerrecipe isEqualToString:appdelegate.strRecipeName]) && timetobefired != nil)
{
NSTimeInterval secondsBetween = [timetobefired timeIntervalSinceDate:currentdate];
NSInteger time = round(secondsBetween);
int second = (int)time;
if(second > 0)
{
secondsLeft = second;
arrForButtonSelection = appdelegate.storingbuttonstate;
[btnOnOff setOn:YES];
if(![timer isValid])
{
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(updateCountdown) userInfo:nil repeats:YES];
}
}
else
{
secondsLeft = 0;
}
}
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(goBackground)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(doMyLayoutStuff:)
name: UIApplicationWillEnterForegroundNotification
object:nil];
}
Change the observer to "self" in your addObserver call
i.e
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(doMyLayoutStuff:)
name: UIApplicationWillEnterForegroundNotification
object:nil];

Change the position of character in string

I have a two string like "SANFRANSICO" and "CHICAGO"
Now i want to make it like the string is in reverse but in a single string like "OOCGIASCNIAHRCFNAS"
I have done code but it gives me wrong result
check out my code
- (NSString *)changeString1:(NSString *)string string2:(NSString *)string2{
int first = [string length];
int second = [string2 length];
int total = first+second;
NSMutableString *str = [[NSMutableString alloc] init];
string = [self reverseString:string];
string2 = [self reverseString:string2];
for (int i=0; i<total+1; i++)
{
if (i%2==1) {
int j = i/2;
if(j < second){
NSString *ichar = [NSString stringWithFormat:#"%c", [string2 characterAtIndex:j]];
[str appendString:ichar];
}
else{
NSString *ichar = [NSString stringWithFormat:#"%c", [string characterAtIndex:j+1]];
NSLog(#"222 %d %#",j+1, ichar );
[str appendString:ichar];
check = YES;
}
}
else {
int j = i/2;
if(check == YES){
}
else{
NSString *ichar = [NSString stringWithFormat:#"%c", [string characterAtIndex:j]];
NSLog(#"1111 %d %#",j, ichar );
[str appendString:ichar];
}
}
}
return str;
}
I found the answer very soon after post this question sorry for posting this question
check out my answer
- (NSString *)changeString1:(NSString *)string string2:(NSMutableString *)string2{
int first = [string length];
int second = [string2 length];
string = [self reverseString:string];
string2 = [self reverseString:string2];
for(int i =second; i<first; i ++){
[string2 appendString:#" "];
}
int total = first*2;
NSMutableString *str = [[NSMutableString alloc] init];
for (int i=0; i<total; i++)
{
if (i%2==1) {
int j = i/2;
if(j < second){
NSString *ichar = [NSString stringWithFormat:#"%c", [string2 characterAtIndex:j]];
[str appendString:ichar];
}
}
else {
int j = i/2;
if(j < first){
NSString *ichar = [NSString stringWithFormat:#"%c", [string characterAtIndex:j]];
[str appendString:ichar];
}
else{
NSString *ichar = [NSString stringWithFormat:#"%c", [string2 characterAtIndex:j]];
[str appendString:ichar];
}
}
}
NSLog(#"str %#", str);
return str;
}

Why application shows low memory warning during heap shot analysis?

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.

parse a NSURL mailto

How can I parse a mailto request ?
'mailto:someone#example.com?cc=someone_else#example.com&subject=This%20is%20the%20subject&body=This%20is%20the%20body'
From this NSURL, I want to extract the recipient, the subject and the body. How should I do ?
Thanks
Here is some code that will parse any URL and return a dictionary with the parameters and the associated objects in a dictionary. It works for mailto URLs, too.
Please note: This code assumes you're using ARC!
#interface NSString (URLDecoding)
- (NSString *) URLDecodedString;
#end
#implementation NSString (URLDecoding)
- (NSString *) URLDecodedString {
NSString *result = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, (__bridge CFStringRef)self, CFSTR(""), kCFStringEncodingUTF8);
return result;
}
#end
- (NSDictionary *) parameterDictionaryFromURL:(NSURL *)url {
NSMutableDictionary *parameterDictionary = [[NSMutableDictionary alloc] init];
if ([[url scheme] isEqualToString:#"mailto"]) {
NSString *mailtoParameterString = [[url absoluteString] substringFromIndex:[#"mailto:" length]];
NSUInteger questionMarkLocation = [mailtoParameterString rangeOfString:#"?"].location;
[parameterDictionary setObject:[mailtoParameterString substringToIndex:questionMarkLocation] forKey:#"recipient"];
if (questionMarkLocation != NSNotFound) {
NSString *parameterString = [mailtoParameterString substringFromIndex:questionMarkLocation + 1];
NSArray *keyValuePairs = [parameterString componentsSeparatedByString:#"&"];
for (NSString *queryString in keyValuePairs) {
NSArray *keyValuePair = [queryString componentsSeparatedByString:#"="];
if (keyValuePair.count == 2)
[parameterDictionary setObject:[[keyValuePair objectAtIndex:1] URLDecodedString] forKey:[[keyValuePair objectAtIndex:0] URLDecodedString]];
}
}
}
else {
NSString *parameterString = [url parameterString];
NSArray *keyValuePairs = [parameterString componentsSeparatedByString:#"&"];
for (NSString *queryString in keyValuePairs) {
NSArray *keyValuePair = [queryString componentsSeparatedByString:#"="];
if (keyValuePair.count == 2)
[parameterDictionary setObject:[[keyValuePair objectAtIndex:1] URLDecodedString] forKey:[[keyValuePair objectAtIndex:0] URLDecodedString]];
}
}
return [parameterDictionary copy];
}
And here is how you use it:
NSURL *mailtoURL = [NSURL URLWithString:#"mailto:foo#example.com?cc=bar#example.com&subject=Greetings%20from%20Cupertino!&body=Wish%20you%20were%20here!"];
NSDictionary *parameterDictionary = [self parameterDictionaryFromURL:mailtoURL];
NSString *recipient = [parameterDictionary objectForKey:#"recipient"];
NSString *subject = [parameterDictionary objectForKey:#"subject"];
NSString *body = [parameterDictionary objectForKey:#"body"];
EDIT:
I updated the code to work with any URL and recipients are now in the dictionary for mailto URLs.
I would pull the email from that like this:
NSString * mailToString = #"'mailto:someone#example.com?cc=someone_else#example.com&subject=This%20is%20the%20subject&body=This%20is%20the%20body'";
NSArray *tempArray = [mailToString componentsSeparatedByString:#"?"];
//get email address from array
NSString * emailString = [[tempArray objectAtIndex:0]description];
//clean up string
emailString = [emailString stringByReplacingOccurrencesOfString:#"'mailto:" withString:#""];
//and here is your email string
NSLog(#"%#",emailString);
Since iOS 7 this is easily doable with NSURLComponents. You can create that object with:
if let components = NSURLComponents(URL: url, resolvingAgainstBaseURL:false) { ...
Then you can get the recipient accessing the path property of NSURLComponents; and the parameters with the queryItems property. For instance, if we wanted to get the subject, something like this would do our job
let queryItems = components.queryItems as? [NSURLQueryItem]
let subject = queryItems?.filter({$0.name == "subject"}).first?.value
NSURL category for just mailto: This method also has a fix for a crash bug in Fabian's answer above when mailto: url doesn't contain a ?. It also doesn't require the URLDecodedString category method.
#implementation NSURL (Additions)
- (NSDictionary *) parameterDictionaryForMailTo {
NSMutableDictionary *parameterDictionary = [[NSMutableDictionary alloc] init];
NSString *mailtoParameterString = [[self absoluteString] substringFromIndex:[#"mailto:" length]];
NSUInteger questionMarkLocation = [mailtoParameterString rangeOfString:#"?"].location;
if (questionMarkLocation != NSNotFound) {
[parameterDictionary setObject:[mailtoParameterString substringToIndex:questionMarkLocation] forKey:#"recipient"];
NSString *parameterString = [mailtoParameterString substringFromIndex:questionMarkLocation + 1];
NSArray *keyValuePairs = [parameterString componentsSeparatedByString:#"&"];
for (NSString *queryString in keyValuePairs) {
NSArray *keyValuePair = [queryString componentsSeparatedByString:#"="];
if (keyValuePair.count == 2)
[parameterDictionary setObject:[[keyValuePair objectAtIndex:1] stringByRemovingPercentEncoding] forKey:[[keyValuePair objectAtIndex:0] stringByRemovingPercentEncoding]];
}
}
else {
[parameterDictionary setObject:mailtoParameterString forKey:#"recipient"];
}
return [parameterDictionary copy];
}
- (NSDictionary *) parameterDictionaryFromURL:(NSURL *)url {
NSMutableDictionary *parameterDictionary = [[NSMutableDictionary alloc] init];
NSURLComponents * urlComponents = [NSURLComponents componentsWithString:url.absoluteString];
for (NSURLQueryItem *item in urlComponents.queryItems) {
parameterDictionary[item.name] = item.value;
}
if ([url.scheme isEqualToString:#"mailto"]) {
NSUInteger questionMarkLocation = [url.resourceSpecifier rangeOfString:#"?"].location;
if (questionMarkLocation == NSNotFound) {
parameterDictionary[#"recipient"] = url.resourceSpecifier;
} else {
parameterDictionary[#"recipient"] = [url.resourceSpecifier substringToIndex:questionMarkLocation];
}
}
return [parameterDictionary copy];
}

Problem in two string comparison...!

LotteryAppDelegate *appDelegate = (LotteryAppDelegate *)[[UIApplication sharedApplication] delegate];
Lotterycheck *check;
//NSString *trueval;
BOOL found = NO;
NSUInteger f;
for (f = 0; f < [appDelegate.books count]; f++) {
check = [appDelegate.books objectAtIndex:f];
checkthis = [NSString stringWithFormat:#"%#", check.LotteryNumber];
mystring =#"1234567"; //check.LotteryNumber;
NSString *finel = checkthis;
NSLog(#"Dynamic Value: %#",finel);
NSLog(#"Static Value: %#",mystring);
if ([mystring isEqualToString:finel]) {
found = YES;
[self showalert:finel];
break;
}
its not comapring the string " if([mystring isEqualToString:finel])" mystring is static value and finel is the value i am getting from the class lotterycheck..
Assuming that an object belonging to appDelegate.books is of class Book, try the following code snippet.
BOOL found = NO;
NSString *mystring = #"1234567";
for (Book *book in appDelegate.books) {
NSString *checkthis = [NSString stringWithFormat:#"%#", book.LotteryNumber];
if ([mystring isEqualToString checkthis]) {
found = YES;
[self showalert:checkthis];
break;
}
}