UIApplicationWillEnterForegroundNotification not called - iphone

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];

Related

objective-c 'double free' error in ARC mode

I'm trying to practice the block and GCD/NSOperation, so I wrote this project Async-objc, but when I'm trying to test it with unit test, I always encountered 'double free' error, I thought there shouldn't be such error in ARC mode.
here is the code
- (void)each:(NSArray *)items iterator:(callbackEach)iterator complete:(callbackWithError)complete {
NSBlockOperation *blockOp = [NSBlockOperation blockOperationWithBlock:^{
if (!items || items.count == 0) {
complete(nil);
return;
}
callbackWithError __block completeOnce = complete;
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSLog(#"start operations %#", queue);
[queue setMaxConcurrentOperationCount:kMaxConcurrentOperationCount];
NSInteger __block count = 0;
for (id item in items) {
NSOperation *op = [NSBlockOperation blockOperationWithBlock:^{
iterator(item, ^(NSError *error) {
if (error) {
completeOnce(error);
completeOnce = nil;
} else {
count++;
if (count >= items.count) {
completeOnce(nil);
completeOnce = nil;
}
}
});
}];
[queue addOperation:op];
}
[queue waitUntilAllOperationsAreFinished];
NSLog(#"all operations are down %#", queue);
}];
[_mainQueue addOperation:blockOp];
}
this is the test code:
- (void)testEachWithBigData {
BOOL __block completed = false;
NSMutableArray *items = [NSMutableArray arrayWithCapacity:100];
for (int i = 1; i < 10000; ++i) {
[items addObject:[NSString stringWithFormat:#"%d", i]];
}
NSMutableArray *result = [NSMutableArray arrayWithCapacity:100];
[_async each:items
iterator:^(id item, callbackWithError callback) {
//NSLog(#"======item %#", item);
NSNumber *num = [NSNumber numberWithInt:[item integerValue]];
//NSLog(#"number %#", num);
[result addObject:num];
callback(nil);
}
complete:^(NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
STAssertNil(error, #"there should be no error");
[result sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSNumber *num1 = (NSNumber *)obj1;
NSNumber *num2 = (NSNumber *)obj2;
if ([num1 integerValue] > [num2 integerValue]) {
return NSOrderedDescending;
} else if ([num1 integerValue] < [num2 integerValue]) {
return NSOrderedAscending;
}
return NSOrderedSame;
}];
NSInteger index = 1;
for (NSNumber *num in result) {
STAssertEquals(index, [num integerValue], #"the value should be ordered");
index++;
}
completed = YES;
});
}
];
NSDate *until = [NSDate dateWithTimeIntervalSinceNow:10];
while (!completed && [until timeIntervalSinceNow] > 0) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:until];
}
}
If you couldn't reproduce the error, increase the test item count to 10000.
for (int i = 1; i < 10000; ++i) {
[items addObject:[NSString stringWithFormat:#"%d", i]];
}
and comment the NSLog()
then Command + U to run the unit test
here is the error message:
otest(11105,0xb039f000) malloc: * error for object 0xa0f8000: pointer being freed was not allocated
otest(11209,0xb0115000) malloc: * error for object 0x41dcc00: pointer being freed was not allocated
* set a breakpoint in malloc_error_break to debug
I cannot reproduce the 'double free' error this time

Adding address book in contact page

I want to add an address book in my contact page and I want to do that programmatically i.e without using nib files. Can anyone suggest me a nice tutorial or sample code for that. i have used the codes of the answer given by iPatel and when i am running it is throwing exception and app is getting terminated.
thanks and regards.
Here is the edited code.
#import "ContactInfoViewController.h"
#interface ContactInfoViewController ()
#end
#implementation ContactInfoViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
self.view.backgroundColor = [UIColor yellowColor];
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:#selector(gotohomepage:)]autorelease];
ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
[[picker navigationBar] setBarStyle:UIBarStyleBlack];
picker.peoplePickerDelegate = self;
NSArray *displayedItems = [NSArray arrayWithObjects:[NSNumber numberWithInt:kABPersonPhoneProperty],nil];
picker.displayedProperties = displayedItems;
[self presentModalViewController:picker animated:YES];
[picker release];
}
- (IBAction)gotohomepage:(id)sender
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
ABAddressBookRef addressBook = ABAddressBookCreate();
int i;
NSString *strName = #"";
NSString* company = #"";
NSString *address = #"";
NSString *suburb = #"";
NSString *postalcode = #"";
NSString *state = #"";
NSString *country = #"";
NSString *mobile = #"";
NSString *phone = #"";
NSString *emailid = #"";
strName = (NSString *)ABRecordCopyCompositeName((ABRecordRef) person);
CFStringRef name = ABRecordCopyCompositeName((ABRecordRef) person);
company = (NSString *)ABRecordCopyValue((ABRecordRef) person, kABPersonOrganizationProperty);
NSArray* allPeople = (NSArray *)ABAddressBookCopyPeopleWithName(addressBook,name);
CFRelease(name);
for (i = 0; i < [allPeople count]; i++)
{
ABRecordRef record = [allPeople objectAtIndex:i];
ABMutableMultiValueRef multiValue = ABRecordCopyValue(record, kABPersonAddressProperty);
for(CFIndex i=0; i<ABMultiValueGetCount(multiValue); i++)
{
NSString* HomeLabel = (NSString*)ABMultiValueCopyLabelAtIndex(multiValue, i);
if([HomeLabel isEqualToString:#"_$!<Home>!$_"])
{
CFDictionaryRef dict = ABMultiValueCopyValueAtIndex(multiValue, i);
address = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressStreetKey)];
suburb = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressCityKey)];
postalcode = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressZIPKey)];
state = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressStateKey)];
country = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressCountryKey)];
CFRelease(dict);
}
CFRelease(HomeLabel);
}
CFRelease(multiValue);
}
CFRelease(allPeople);
ABMultiValueRef phones =(NSString*)ABRecordCopyValue(person, kABPersonPhoneProperty);
NSString* mobileLabel = nil;
for(CFIndex i = 0; i < ABMultiValueGetCount(phones); i++)
{
mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phones, i);
if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
{
mobile = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
NSLog(#"phone %#",mobile);
}
else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
{
phone = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
NSLog(#"phone %#",phone);
CFRelease(mobileLabel);
break ;
}
CFRelease(mobileLabel);
}
CFStringRef value, label;
ABMutableMultiValueRef multi = ABRecordCopyValue(person, kABPersonEmailProperty);
CFIndex count = ABMultiValueGetCount(multi);
if (count == 1)
{
value = ABMultiValueCopyValueAtIndex(multi, 0);
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
CFRelease(value);
}
else
{
for (CFIndex i = 0; i < count; i++)
{
label = ABMultiValueCopyLabelAtIndex(multi, i);
value = ABMultiValueCopyValueAtIndex(multi, i);
if (CFStringCompare(label, kABWorkLabel, 0) == 0)
{
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
}
else if(CFStringCompare(label, kABHomeLabel, 0) == 0)
{
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
}
CFRelease(label);
CFRelease(value);
}
}
CFRelease(multi);
CFRelease(phones);
CFRelease(addressBook);
[self dismissModalViewControllerAnimated:YES];
return NO;
}
#pragma mark - ABPeopelPickerNavigationController Delegate and DataSource Methods
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
[self dismissModalViewControllerAnimated:YES];
}
- (void)unknownPersonViewController:(ABUnknownPersonViewController *)unknownCardViewController didResolveToPerson:(ABRecordRef)person
{
}
- (void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(ABRecordRef)person
{
}
- (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
return YES;
}
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier;
{
return YES;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#end
EDIT :
First Add all Delegate and Datasource method in your class .h file
<ABPeoplePickerNavigationControllerDelegate,ABPersonViewControllerDelegate,ABNewPersonViewControllerDelegate,ABUnknownPersonViewControllerDelegate>
Create ABPeoplePickerNavigationController
ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
[[picker navigationBar] setBarStyle:UIBarStyleBlack];
picker.peoplePickerDelegate = self;
// Display only a person's phone, email, and birthdate
NSArray *displayedItems = [NSArray arrayWithObjects:[NSNumber numberWithInt:kABPersonPhoneProperty],nil];
picker.displayedProperties = displayedItems;
// Show the picker
[self presentModalViewController:picker animated:YES];
[picker release];
Add Following Delegate and DataSource method of ABPeopelPickerNavigationController
#pragma mark - ABPeopelPickerNavigationController Delegate and DataSource Methods
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
[self dismissModalViewControllerAnimated:YES];
}
- (void)unknownPersonViewController:(ABUnknownPersonViewController *)unknownCardViewController didResolveToPerson:(ABRecordRef)person
{
}
- (void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(ABRecordRef)person
{
}
- (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
return YES;
}
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier;
{
return YES;
}
please try below code for get all the information of people from phonebook
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
ABAddressBookRef addressBook = ABAddressBookCreate();
int i;
NSString *strName = #"";
NSString* company = #"";
NSString *address = #"";
NSString *suburb = #"";
NSString *postalcode = #"";
NSString *state = #"";
NSString *country = #"";
NSString *mobile = #"";
NSString *phone = #"";
NSString *emailid = #"";
strName = (NSString *)ABRecordCopyCompositeName((ABRecordRef) person);
CFStringRef name = ABRecordCopyCompositeName((ABRecordRef) person);
company = (NSString *)ABRecordCopyValue((ABRecordRef) person, kABPersonOrganizationProperty);
NSArray* allPeople = (NSArray *)ABAddressBookCopyPeopleWithName(addressBook,name);
CFRelease(name);
for (i = 0; i < [allPeople count]; i++)
{
ABRecordRef record = [allPeople objectAtIndex:i];
ABMutableMultiValueRef multiValue = ABRecordCopyValue(record, kABPersonAddressProperty);
for(CFIndex i=0; i<ABMultiValueGetCount(multiValue); i++)
{
NSString* HomeLabel = (NSString*)ABMultiValueCopyLabelAtIndex(multiValue, i);
if([HomeLabel isEqualToString:#"_$!<Home>!$_"])
{
CFDictionaryRef dict = ABMultiValueCopyValueAtIndex(multiValue, i);
address = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressStreetKey)];
suburb = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressCityKey)];
postalcode = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressZIPKey)];
state = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressStateKey)];
country = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressCountryKey)];
CFRelease(dict);
}
CFRelease(HomeLabel);
}
CFRelease(multiValue);
}
CFRelease(allPeople);
ABMultiValueRef phones =(NSString*)ABRecordCopyValue(person, kABPersonPhoneProperty);
NSString* mobileLabel = nil;
for(CFIndex i = 0; i < ABMultiValueGetCount(phones); i++)
{
mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phones, i);
if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
{
mobile = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
NSLog(#"phone %#",mobile);
}
else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
{
phone = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
NSLog(#"phone %#",phone);
CFRelease(mobileLabel);
break ;
}
CFRelease(mobileLabel);
}
CFStringRef value, label;
ABMutableMultiValueRef multi = ABRecordCopyValue(person, kABPersonEmailProperty);
CFIndex count = ABMultiValueGetCount(multi);
if (count == 1)
{
value = ABMultiValueCopyValueAtIndex(multi, 0);
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
CFRelease(value);
}
else
{
for (CFIndex i = 0; i < count; i++)
{
label = ABMultiValueCopyLabelAtIndex(multi, i);
value = ABMultiValueCopyValueAtIndex(multi, i);
// check for Work e-mail label
if (CFStringCompare(label, kABWorkLabel, 0) == 0)
{
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
}
else if(CFStringCompare(label, kABHomeLabel, 0) == 0)
{
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
}
CFRelease(label);
CFRelease(value);
}
}
CFRelease(multi);
}
CFRelease(phones);
CFRelease(addressBook);
[self dismissModalViewControllerAnimated:YES];
return NO;
}
For more information read this and this tutorial.
Thanks :)

NSTimer stops when we click on ScrollView

In my app am using UIScrollView which is having UIImageView(20) to add images iused the - (void)populateScrollView method.
- (void)populateScrollView
{
TonifyAppDelegate *appDelegate = (TonifyAppDelegate *)[UIApplication sharedApplication].delegate;
double x1 = 0, y1 = 3;
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
NSMutableArray *getEffectsImageData = [ud objectForKey:#"getimageeffects"];
imageViewsArray = [[NSMutableArray alloc] initWithCapacity:[getEffectsImageData count]];
for(int i = 0; i < [getEffectsImageData count]; i++)
{
NSString *sfxUrlFileName = [ [getEffectsImageData objectAtIndex:i] lastPathComponent];
NSLog(#"sfxUrlFileName: %#", sfxUrlFileName);
NSData *imageData = [appDelegate readSongDataFromDocsDirectory:sfxUrlFileName];
UIImage *image = [[UIImage alloc] initWithData:imageData];
UIImageView *anImageView = [[UIImageView alloc]initWithImage:image];
CGRect imageFrame = anImageView.frame;
imageFrame.origin.x = x1;
imageFrame.origin.y = y1;
anImageView.frame = CGRectMake(x1, y1, 45, 41);
anImageView.userInteractionEnabled = YES;
[scrollView addSubview:anImageView];
x1 += anImageView.frame.size.width + 3;
if (anImageView && [anImageView isMemberOfClass: [UIImageView class]])
[imageViewsArray addObject: anImageView];
}
NSLog(#"imageViewsArray:%#",imageViewsArray);
}
And to recognize touch in UIScrollView i used
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(singleTapGestureCaptured:)];
[scrollView addGestureRecognizer:singleTap];
Meanwhile am running song by using NSTimer which is like
myTimer = [NSTimer scheduledTimerWithTimeInterval:timeinterval target:self selector:#selector(**updatplayer**) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:myTimer forMode:NSRunLoopCommonModes];
in updatePlayer method am doing task as follows
- (void)updatplayer
{
TonifyAppDelegate *appDelegate = (TonifyAppDelegate *)[UIApplication sharedApplication].delegate;
if (mThresholdVal<mMainLoopLength)
{
mThresholdVal+=0.5;
}
else
{
mThresholdVal = 0.0;
}
if (divimageView)
{
[divimageView removeFromSuperview];
}
if ([self isHeadsetPluggedIn]==NO) {
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
}
else
{
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_None;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
}
NSString *cu=[NSString stringWithFormat:#"%2.f",audioPlayer.currentTime];
NSString *du=[NSString stringWithFormat:#"%2.f",audioPlayer.duration];
NSLog(#"LOOP cu Duration = %#",cu);
NSLog(#"LOOP du = %#",du);
int curenttime=(int)[cu intValue];
NSLog(#"LOOP current Duration = %2.f",audioPlayer.duration);
if(curenttime==0)
{
[audioPlayer play];
x=20;
}
mixdata = [NSMutableDictionary dictionary];
{
[activityIndicator stopAnimating];
activityIndicator.hidden = YES;
[divimageView setFrame:CGRectMake(x, 87, 12, 144)];
[self.view addSubview:divimageView];
x=x+1;
if ((x>19 && x< 480) && appDelegate.songURL != NULL) {
[avplayer play];
NSLog(#"mixdata:%#", mixdata);
}
else if((x>19 && x< 480) && (appDelegate.songIntroUrl || appDelegate.songMidUrl || appDelegate.songChorusUrl) )
{
[audioPlayer play];
}
if (x==xCord && yCord<235)
{
[audioPlayer1 play];
}
if (x==recXcord)
{
recaudioPlayer.volume = 10.0;
[recaudioPlayer play];
[activityIndicator stopAnimating];
activityIndicator.hidden = YES;
}
if(appDelegate.xCordArray!=NULL && [appDelegate.tagArray count]>0)
{
for(int i = 0; i<[appDelegate.xCordArray count];i++)
{
if (i == 0){
NSLog(#"sfxCount in i==0......%d",sfxCount);
NSLog(#"[appDelegate.xCordArray count] in i==0......%d",[appDelegate.xCordArray count]);
NSLog(#"[appDelegate.mMixedSFXTrack2Array count] in i==0......%d",[appDelegate.mMixedSFXTrack2Array count]);
if (sfxCount-1 != [appDelegate.xCordArray count])
{
if ([appDelegate.xCordArray count] > [appDelegate.mMixedSFXTrack2Array count] )
{
mShouldBufferUpdate = TRUE;
sfxCount = [appDelegate.xCordArray count];
}
}
}
if (x==[[appDelegate.xCordArray objectAtIndex:i] intValue] && appDelegate.imgDragXCodr<480)
{
int j = [[appDelegate.tagArray objectAtIndex:i] intValue];
//mShouldBufferUpdate = TRUE;
[self getSetSongData:j :x];
[audioPlayer2 play];
}
}
}
if(appDelegate.xCordTrack3Array!=NULL && [appDelegate.track3tagArray count]>0)
{
for(int i = 0; i<[appDelegate.xCordTrack3Array count];i++)
{
if (i == 0)
{
if (sfxCount3-1 != [appDelegate.xCordTrack3Array count])
{
if ([appDelegate.xCordTrack3Array count] > [appDelegate.mMixedSFXTrack3Array count] )
{
mShouldBuffer3Update = TRUE;
sfxCount3 = [appDelegate.xCordTrack3Array count];
}
}
}
if (x==[[appDelegate.xCordTrack3Array objectAtIndex:i] intValue] && appDelegate.imgDragXCodr1<480)
{
int j = [[appDelegate.track3tagArray objectAtIndex:i] intValue];
[self getSetSongData:j :x];
[trac3AudioPlayer play]; //For SFX Sounds
}
}
}
if (x == 480)
{
x=20;
}
}
}
When i click on scrollView it generates an image in UIView(main View) at that time NSTimer is getting paused.
How can we solve this.
Any one can help or suggest me.
Thanks in advance.

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.

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.