Code works fine on iOS5 but not on iOS4.3 - iphone

I have code that works fine on iOS5 but does not work on iOS4.3, I'm trying to display a loading screen with a progress bar from a navigation controller that has a UIViewController as the root view.
The problem is that on iOS4.3 the loading screen doesn't appear at the right time, it appears just before the view of the second view controller is displayed and then disappears quickly.
Here's the code :
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
NSUserDefaults * standardUserDefaults = [NSUserDefaults standardUserDefaults];
CGSize s = [[UIScreen mainScreen] bounds].size;
[standardUserDefaults setObject:#"" forKey:#"display_resolution"];
if((int)s.width == 640 && (int)s.height == 960)[standardUserDefaults setObject:#"#2x" forKey:#"display_resolution"];
[standardUserDefaults synchronize];
AC_Loading *loading = [[[AC_Loading alloc] initWithNibName:#"AC_Loading_iPhone" bundle:nil] autorelease];
_navController0 = [[[UINavigationController alloc]initWithRootViewController:loading]autorelease];
_navController0.navigationBar.hidden = YES;
self.window.rootViewController = self.navController0;
[self.window makeKeyAndVisible];
return YES;
}
-
Edit
I figured out that the problem came from AC_Loading's code, this UIViewController has to display a loading screen with a progress view that updates according to database stat (I'm creating a sqlite3 database and updating it if needed and showing progress).While using this code on iOS5 works but it doesn't on iOS4.x I thought is because of the loop inside viewDidAppear (While pr<1.0):
#import "AC_Loading.h"
#import "database.h"
#import "AC_Menu.h"
#implementation AC_Loading
#synthesize logo;
#synthesize progress;
#synthesize informations;
#synthesize CLController;
float pr = 0.14;
int p = 0;
AC_Menu *menu;
NSUserDefaults *standardUserDefaults;
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)viewDidLoad
{
[super viewDidLoad];
standardUserDefaults = [NSUserDefaults standardUserDefaults];
[standardUserDefaults setObject:#"NO" forKey:#"geoloc"];
[standardUserDefaults synchronize];
NSLog(#"%#", [NSString stringWithFormat:#"intro%#%#", [standardUserDefaults stringForKey:#"display_resolution"], #".jpg"]);
[logo setImage:[UIImage imageNamed:[NSString stringWithFormat:#"intro%#%#", [standardUserDefaults stringForKey:#"display_resolution"], #".jpg"]]];
//[progress setProgressTintColor:[UIColor purpleColor]];
[progress setProgress:0.14];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[self setLogo:nil];
[self setInformations:nil];
[self setProgress:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:YES];
database *DB = [[database alloc] init];
[DB checkDB];
NSString *message = #"Chargement des données";
if([DB isCreated]== NO && [DB upToDate] == NO && sqlite3_open([[DB getDBPath:[NSString stringWithFormat:#"%#%#%#", #"Restaurant_V", [DB getVersion], #".sqlite" ]] UTF8String], [DB getDB]) == SQLITE_OK)
{
message = #"Mise à jour des données";
[DB setExecuting:YES];
[NSThread detachNewThreadSelector:#selector(createDB) toTarget:DB withObject:nil];
while([DB isExecuting]==YES)
{
if([DB isExecuting]==NO) break;
}
NSLog(#"Cas 1");
}
if([DB isCreated]== YES && [DB upToDate] == NO && sqlite3_open([[DB getDBPath:[NSString stringWithFormat:#"%#%#%#", #"Restaurant_V", [DB getVersion], #".sqlite" ]] UTF8String], [DB getDB]) == SQLITE_OK)
{
[DB setExecuting:YES];
[NSThread detachNewThreadSelector:#selector(updateDB:) toTarget:DB withObject:[DB getVersion]];
while([DB isExecuting]==YES)
{
if([DB isExecuting]==NO) break;
}
NSLog(#"Cas 2");
}
int p = floor([progress progress]*100);
while (pr<1.0)
{
p = floor(pr*100);
if(p%14==0)
{
CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0, true);
[progress setProgress:pr];
[informations setText:[NSString stringWithFormat:#"%# (%d%#", message, p, #"%)"]];
}
pr += 0.000002;
}
[progress setProgress:1.0];
[informations setText:[NSString stringWithFormat:#"%# (100%#", message, #"%)"]];
menu =
[[[AC_Menu alloc] initWithNibName:#"AC_Menu_iPhone" bundle:nil] autorelease];
[self.navigationController pushViewController:menu animated:YES];
[DB release];
CLController = [[CoreLocationController alloc] init];
CLController.delegate = self;
[CLController.locMgr startUpdatingLocation];
}
- (void)dealloc {
[CLController release];
[logo release];
[informations release];
[progress release];
[super dealloc];
}

Related

'wait_fences: failed to receive reply: 10004003' in iPhone

My application crash when I pop to root view controller in click event of UIAlertView.
my code as below :
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0 && ([errorCodeNew isEqualToString:#"IPH_I_LGN_002"])){
[self.navigationController popToRootViewControllerAnimated:YES];
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:#"3" forKey:#"CurrentSize"];
NSMutableArray *nsmarrJpName;
DatabaseLogic *logic = [[DatabaseLogic alloc] init];
appDelegate.anket_id = [logic getAnketID];
nsmarrJpName = [[NSMutableArray alloc]initWithArray:[logic getDetailScreenItems:[logic getAnketID]] copyItems:YES];
for (int i = 0; i < [nsmarrJpName count]; i++) {
NSString *strKey = [nsmarrJpName objectAtIndex:i];
[defaults setObject: [NSNumber numberWithBool:YES] forKey:strKey];
NSLog(#"key : %#", strKey);
}
[nsmarrJpName removeAllObjects];
[nsmarrJpName release];
appDelegate.strUserFlg = [logic getUserType];
[logic release]; logic = nil;
//start download process
[[NSNotificationCenter defaultCenter] postNotificationName:LOGIN_COMPLETE_NOTIFICATION object:self userInfo:nil];
}else{
NSLog(#"cancel");
}
}
I have tried by replacing clickedButtonAtIndex with didDismissWithButtonIndex method. But I does not get any result.
Thanks.
Try moving the [self.navigationController popToRootViewControllerAnimated:YES] to the bottom of the function (i.e. after all the other code has run).

iCloud and CoreData

I am trying to use iCloud with my iOS app. I have the app working on the individual devices but when I added iCloud nothing happened. I have looked all over the web and have found only one example which I did not understand. My app is iOS 5.0 and use core data to store the pages. Below is my app delegate and my view which I display it in. Sorry for the lack of knowledge when it comes to iPhone dev. Please help.
http://goddess-gate.com/dc2/index.php/post/452
thank you
If anyone know/has a full working project of iCloud+CoreData I belive I can figure it out. Right now I just have code snip it's which I don't even know how they get called... If I have a full project I can step through it, so I can fully understand how it works.
The problem is I don't think anything is being called to update the view with the data and I don't belive it is sending it to the cloud but I don't know what to call...
PageFlipperAppDelegate.h
#import <UIKit/UIKit.h>
#import "PageView.h"
#import "SlideShowViewController.h"
#import "PagesCollectionViewController.h"
#import "UiWindowSubclass.h"
#interface PageFlipperAppDelegate : UIResponder <UIApplicationDelegate>
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
#property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
#property (nonatomic, retain, readonly) PagesCollectionViewController *collectionViewController;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
#end
PageFlipperAppDelegate.m
#import "PageFlipperAppDelegate.h"
#implementation PageFlipperAppDelegate
#synthesize window;
#synthesize managedObjectContext, managedObjectModel, persistentStoreCoordinator,collectionViewController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
[NSThread sleepForTimeInterval:2.75];
collectionViewController = [[PagesCollectionViewController alloc] initWithManagedObjectContext:[self managedObjectContext]];
[(UINavigationController *)[[self window] rootViewController] pushViewController:collectionViewController animated:NO];
[collectionViewController release];
[[self window] makeKeyAndVisible];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
//stopping timer since we're going to background
// [(UiWindowSubclass *)self.window stopTimer];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
}
- (void)applicationDidEnterBackground:(UIApplication *)application { [self saveContext]; }
- (void)applicationWillEnterForeground:(UIApplication *)application
{
}
- (void)applicationWillTerminate:(UIApplication *)application { [self saveContext];
}
- (void)dealloc
{
[window release];
[managedObjectContext release];
[managedObjectModel release];
[persistentStoreCoordinator release];
[super dealloc];
}
- (void)awakeFromNib
{
}
- (void)saveContext
{
NSError *error = nil;
if ([self managedObjectContext])
{
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
#pragma mark - Core Data stack
- (NSManagedObjectContext *)managedObjectContext
{
if (managedObjectContext != nil)
{
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
//if (IOS_VERSION_GREATER_THAN_OR_EQUAL_TO(#"5.0")) {
NSManagedObjectContext* moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[moc performBlockAndWait:^{
[moc setPersistentStoreCoordinator: coordinator];
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(mergeChangesFrom_iCloud:) name:NSPersistentStoreDidImportUbiquitousContentChangesNotification object:coordinator];
}];
managedObjectContext = moc;
}
return managedObjectContext;
}
/**
Returns the managed object model for the application.
If the model doesn't already exist, it is created from the application's model.
*/
- (NSManagedObjectModel *)managedObjectModel
{
if (!managedObjectModel)
{
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"PageFlipper" withExtension:#"momd"];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
}
return managedObjectModel;
}
/**
Returns the persistent store coordinator for the application.
If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (persistentStoreCoordinator != nil)
{
return persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"PageFlipper.sqlite"];
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSPersistentStoreCoordinator* psc = persistentStoreCoordinator;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSFileManager *fileManager = [NSFileManager defaultManager];
// Migrate datamodel
NSDictionary *options = nil;
// this needs to match the entitlements and provisioning profile
NSURL *cloudURL = [fileManager URLForUbiquityContainerIdentifier:#"G88FQ4WK29.com.brandonsdesigngroup.3Doodles"];
NSString* coreDataCloudContent = [[cloudURL path] stringByAppendingPathComponent:#"data"];
if ([coreDataCloudContent length] != 0) {
// iCloud is available
cloudURL = [NSURL fileURLWithPath:coreDataCloudContent];
options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
#"3Doodles.store", NSPersistentStoreUbiquitousContentNameKey,
cloudURL, NSPersistentStoreUbiquitousContentURLKey,
nil];
} else {
// iCloud is not available
options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
nil];
}
NSError *error = nil;
[psc lock];
if (![psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
[psc unlock];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"asynchronously added persistent store!");
[[NSNotificationCenter defaultCenter] postNotificationName:#"RefetchAllDatabaseData" object:self userInfo:nil];
});
});
return persistentStoreCoordinator;
}
- (void)mergeiCloudChanges:(NSNotification*)note forContext:(NSManagedObjectContext*)moc {
[moc mergeChangesFromContextDidSaveNotification:note];
NSNotification* refreshNotification = [NSNotification notificationWithName:#"RefreshAllViews" object:self userInfo:[note userInfo]];
[[NSNotificationCenter defaultCenter] postNotification:refreshNotification];
}
- (void)mergeChangesFrom_iCloud:(NSNotification *)notification {
NSManagedObjectContext* moc = [self managedObjectContext];
// this only works if you used NSMainQueueConcurrencyType
// otherwise use a dispatch_async back to the main thread yourself
[moc performBlock:^{
[self mergeiCloudChanges:notification forContext:moc];
}];
}
#pragma mark - Application's Documents directory
/**
Returns the URL to the application's Documents directory.
*/
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
#end
viewController.h
#import <Foundation/Foundation.h>
#import "CollectionViewController.h"
#import "SlideShowViewController.h"
#import "PagesDataSource.h"
#import "PageView.h"
#import "PageViewController.h"
#import "PrototypeView.h"
#import "QuickStart.h"
#interface PagesCollectionViewController : CollectionViewController<quickStartDismiss,NSFetchedResultsControllerDelegate>
{
PagesDataSource *dataSource;
PageViewController *viewController;
#private NSFetchedResultsController *fetchedResultsController__ ;
#private NSManagedObjectContext *managedObjectContext__;
}
#property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;
#property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
- (id)initWithManagedObjectContext:(NSManagedObjectContext *)managedObjectContext;
- (IBAction)add:(id)sender;
-(void)setShadowAndColor;
-(void)playSlideShow;
#property (nonatomic, readwrite, assign) BOOL editMode;
#end
#interface PageView (CollectionViewItem)
- (void)setRepresentedObject:(PVPage *)representedObject;
- (PVPage *)representedObject;
-(void)didHoldItem;
-(void)duplicatePage;
#end
#interface PushController : UIViewController
{}
#end
#interface toolBar : UIToolbar
#end
viewController.m
#import "PagesCollectionViewController.h"
#import "PageFlipperAppDelegate.h"
#implementation toolBar
- (void)drawRect:(CGRect)rect {}
#end
#implementation PagesCollectionViewController
#synthesize editMode;
#synthesize fetchedResultsController=__fetchedResultsController;
#synthesize managedObjectContext=__managedObjectContext;
-(void)viewWillAppear:(BOOL)animated{
if (![[NSUserDefaults standardUserDefaults] integerForKey:#"integerKey"]) {
[[NSUserDefaults standardUserDefaults] setInteger:1 forKey:#"integerKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
QuickStart*stickieViewController = [[[QuickStart alloc]init]autorelease];
stickieViewController.delegate = self;
stickieViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController:stickieViewController animated:YES];
}
[[self navigationController] setNavigationBarHidden:NO animated:NO];
[[self navigationController] setToolbarHidden:NO animated:NO];
[[[self navigationController] toolbar] setBarStyle:UIBarStyleBlackTranslucent];
[self setToolbarItems:[NSArray arrayWithObjects:
[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease],
[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:self action:#selector(playSlideShow)]autorelease],
[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease],
nil]];
[(CollectionView*)[self view] setCanReloadData:YES];
[(CollectionView*)[self view]layoutSubviews];
}
- (NSFetchedResultsController *)fetchedResultsController
{
if (__fetchedResultsController != nil)
{
return __fetchedResultsController;
}
/*
Set up the fetched results controller.
*/
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Page" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptorName = [[NSSortDescriptor alloc] initWithKey:#"<sort key>" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptorName, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:#"<section name key path>" cacheName:#"<cache name>"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptorName release];
[sortDescriptors release];
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return __fetchedResultsController;
}
// because the app delegate now loads the NSPersistentStore into the NSPersistentStoreCoordinator asynchronously
// we will see the NSManagedObjectContext set up before any persistent stores are registered
// we will need to fetch again after the persistent store is loaded
- (void)reloadFetchedResults:(NSNotification*)note {
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
if (note) {
[(CollectionView*)[self view] setCanReloadData:YES];
[(CollectionView*)[self view]layoutSubviews];
}
}
-(void) playSlideShow{
SlideShowViewController *slideShowViewController = [[[SlideShowViewController alloc] init]autorelease];
NSMutableArray *tempArrayOfImages = [[[NSMutableArray alloc] init]autorelease];
for (int i = 0; i < [[dataSource pages]count]; i++) {
if ([[[dataSource pages] objectAtIndex:i] thumbnail] != nil) {
[tempArrayOfImages addObject: [[[dataSource pages] objectAtIndex:i] thumbnail]];
}
}
[[self navigationController] pushViewController:slideShowViewController animated:YES];
[slideShowViewController setImagesInImageViewer:tempArrayOfImages];
}
-(void)dismissQuickStart{
[self dismissModalViewControllerAnimated:YES];
}
- (id)initWithManagedObjectContext:(NSManagedObjectContext *)managedObjectContext
{
if ((self = [super initWithNibName:#"CollectionView" bundle:nil]))
{
if (editMode == NO) {
[self finishEditToolBars];
}
[self setTitle:#"Doodles"];
viewController = [[PageViewController alloc] initWithManagedObjectContext:managedObjectContext];
dataSource = [[PagesDataSource alloc] initWithManagedObjectContext:managedObjectContext];
CGSize itemViewMarginSize = CGSizeMake(25.0, 0.0);
[(CollectionView *)[self view] setItemViewMarginSize:itemViewMarginSize];
PrototypeView *pro = [[[PrototypeView alloc] init] autorelease];
[(CollectionView *)[self view] setItemViewPrototype:pro];
[(CollectionView *)[self view] setFlowDirection:CVFlowDirectionVertical];
[(CollectionView *)[self view] setItemViewFrameSize:CGSizeMake(([(CollectionView *)[self view] bounds].size.width - 3*itemViewMarginSize.width)/3.4, ([(CollectionView *)[self view] bounds].size.height - 3*itemViewMarginSize.height)/3.6)];
[self setShadowAndColor];
}
return self;
}
-(void)setShadowAndColor{
CollectionView *collectionView = (CollectionView *)[self view];
[collectionView setShadowColor:[UIColor blackColor]];
[collectionView setShadowRadius:6.0f];
[collectionView setShadowOpacity:0.5f];
}
- (void)add:(id)sender
{
[dataSource add:sender];
CollectionView *collectionView = (CollectionView *)[self view];
// [collectionView reloadData];
// [collectionView scrollItemIndexToVisible:[self countOfItemsInCollectionView:collectionView]-1 animated:NO];
[collectionView.dataDelegate collectionView:collectionView didSelectItemAtIndex:[self countOfItemsInCollectionView:collectionView]-1];
//CollectionViewController *c;
// [[c transitionToDetailViewController:[c collectionView:self detailViewControllerForItemAtIndex:(NSUInteger)[self countOfItemsInCollectionView:collectionView]-1] forItemView:[itemViews objectForKey:[NSString stringWithFormat:#"%u", [self countOfItemsInCollectionView:collectionView]-1]]]];
// [c transitionToDetailViewController:self forItemView:collectionView.itemViews;
editMode = NO;
//collectionView.canUpdateLayout = YES;
collectionView.canReloadData = YES;
[(CollectionView*)[self view]layoutSubviews];
}
- (NSUInteger)countOfItemsInCollectionView:(CollectionView *)collectionView { return [[dataSource pages] count]; }
- (id)collectionView:(CollectionView *)collectionView representedObjectAtIndex:(NSUInteger)itemIndex {
return [[dataSource pages] objectAtIndex:itemIndex];
}
- (void)collectionView:(CollectionView *)collectionView didSelectItemAtIndex:(NSUInteger)itemIndex
{
if (editMode == YES) {
[collectionView yellowdidSelectItemAtIndex:itemIndex];
// NSLog(#"edit");
}else{
PVPage *selectedPage = [[[dataSource pages] objectAtIndex:itemIndex]autorelease];
PageView *pageView = [[[PageView alloc] init] autorelease];
[pageView setRepresentedPage:selectedPage];
// UIImage *i = [UIImage imageWithData: [[pageView representedPage] thumbnail]];
// UIImageView *ii = [[[UIImageView alloc] initWithImage:i]autorelease];
[viewController setView:pageView];
// [(PageView*)[viewController view] setBackgroundStrokes:ii];
//NSLog(#"selected page %#",selectedPage);
// [[[self navigationController] toolbar] setHidden:YES];
// [[[self navigationController] navigationBar] setHidden:YES];
// [[[self tabBarController] tabBar] setHidden:YES];
PageFlipperAppDelegate *appDelegate = (PageFlipperAppDelegate *)[[UIApplication sharedApplication] delegate];
// [(UiWindowSubclass *)appDelegate.window startTimer];
[(UINavigationController *)[(UiWindowSubclass*)[appDelegate window] rootViewController] pushViewController:viewController animated:YES];
// viewController = nil;
// [[self navigationController] setToolbarHidden:NO];
}
}
- (BOOL)collectionView:(CollectionView *)collectionView canDeleteItemAtIndex:(NSUInteger)itemIndex {
NSLog(#"itemIndex %u",itemIndex);
return YES;
}
- (void)collectionView:(CollectionView *)collectionView didDeleteItemAtIndex:(NSUInteger)itemIndex
{
[dataSource removePageAtIndex:itemIndex];
}
-(void)trash{
// NSLog(#"trash");
[(CollectionView *)[self view] trashitems];
}
-(void)done{
[(CollectionView *)[self view] yellowdidSelectItemAtIndexUndo];
[(CollectionView *)[self view] shakedidRemoveSelectItemAtIndex];
[(CollectionView *)[self view] donereset];
[self finishEditToolBars];
}
-(void) finishEditToolBars{
[[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(add:)] autorelease]];
[[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:#selector(didHoldItem)] autorelease]];
editMode = NO;
}
-(void)duplicatePage{
NSArray *tempArray = [[[(CollectionView*)[self view] selectedItemsArray]copy]autorelease];
// for (int i =0; i<[[(CollectionView*)[self view] selectedItemsArray]count]; i++) {
// [(CollectionView *)[self view] yellowdidSelectItemAtIndex:i];
//
// }
[dataSource duplicatePage:[[[NSArray alloc] initWithArray:tempArray]autorelease]];
CollectionView *collectionView = (CollectionView *)[self view];
editMode = NO;
[self done];
// [(CollectionView *)[self view] yellowdidSelectItemAtIndexUndo];
collectionView.canReloadData = YES;
[collectionView layoutSubviews];
}
-(void)didHoldItem{
[[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(done)] autorelease]];
// [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:#selector(trash)] autorelease]];
toolBar* tools = [[toolBar alloc] initWithFrame:CGRectMake(0, 0, 133, 44.01)];
tools.barStyle = UIBarStyleBlackTranslucent;
tools.opaque = NO;
//tools.backgroundColor = [UIColor clearColor];
// create the array to hold the buttons, which then gets added to the toolbar
NSMutableArray* buttons = [[NSMutableArray alloc] initWithCapacity:3];
// create a standard "add" button
UIBarButtonItem* bi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:#selector(trash)];
bi.style = UIBarButtonItemStyleBordered;
[buttons addObject:bi];
[bi release];
// create a spacer
bi = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
[buttons addObject:bi];
[bi release];
// create a standard "refresh" button
bi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize target:self action:#selector(duplicatePage)];
bi.style = UIBarButtonItemStyleBordered;
[buttons addObject:bi];
[bi release];
// stick the buttons in the toolbar
[tools setItems:buttons animated:NO];
[buttons release];
// and put the toolbar in the nav bar
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:tools] autorelease];
[tools release];
[(CollectionView*)[self view] setOldItemIndex:-1];
editMode = YES;
[(CollectionView*)[self view] setEditMode:YES];
[(CollectionView*)[self view] shakedidSelectItemAtIndex];
}
-(void)didReceiveMemoryWarning{
// NSLog(#"mem");
}
- (void)dealloc
{ [dataSource release],dataSource = nil;
[viewController release],viewController = nil;
[super dealloc];
}
-(void)viewDidAppear:(BOOL)animated{
[ (CollectionView*) [self view] setCanReloadData:YES];
[(CollectionView*) [self view] layoutSubviews];
}
-(void) viewDidLoad{
CollectionView *collectionView = (CollectionView *)[self view];
collectionView.canReloadData = YES;
[(CollectionView*)[self view]layoutSubviews];
editMode = NO;
collectionView.editMode = NO;
}
#end
On the Apple developer forums the iPhoneCoreDataRecipes sample code is posted, which includes iCloud.
https://devforums.apple.com/thread/126670?tstart=0
You can watch this year's WWDC 2012 Session 227 lecture (you can freely access these videos using your Apple Developer account), that will show how to correctly use Core Data and iCloud together, illustrating the correct application architecture, the way Core Data and iCloud should talk to each other and explaining all this stuff through a complete sample project.
Edit
The full source of the project is only available to all registered Apple developers under this page.
This is a very controversial topic... I need to add iCloud with Core Data in my next application but it's a bit hard to start. I have done nothing but I found these documents very useful:
Using Core Data with iCloud Release Notes
Using iCloud in Conjunction with Databases
Your Third iOS App: iCloud
It's not just controversial, it's not working adequately yet. If you are able to code the sample, you'll likely find that it only works on occasion. I wish I could write that it's solved and here is how you use it - maybe someone else can, but as of March 2012, I doubt it.
Still, it's interesting and instructive to code the sample, and the others in the dev site, so that you can learn what iCloud/core data is all about.
A lot of us are chomping at the bit for this to solidify.
You may want to try Dox from Ray Wenderlich's fantastic site. But you'll likely end up with the same frustration. Sometimes it works, mostly not.
Blackpixel have upped a version of Core Data Recipes with iCloud to Github. It may have improvements over the version in the dev forums.
I've used the dev forums version and found that it works, but takes some time to sync. Read the comments thread there (19 pages and counting) and make up your mind about it.

Possible memory leak

I know this is a very stupid question to ask but i have a view controller which has a mapview in it and some uibuttons i have done every thng to eliminate all the leaks bt still after 2-3 toggle between two controller app crashs. Below is the code for allocation and dellocation. BTW i dont get any "did recive memoru warning".. Thnx alot
.h/
#interface MapView : BaseViewController <MKMapViewDelegate,MKAnnotation> {
MKMapView *mapView;
NSMutableArray *placeName;
NSString *mid;
UISegmentedControl *segmentedControl;
IBOutlet UILabel *numberofbeeps;
NSInteger badgenumber;
}
#property (nonatomic, retain) UILabel *numberofbeeps;
#property(nonatomic, retain) NSString *mid;
#property (nonatomic, retain) IBOutlet MKMapView *mapView;
#property(nonatomic,retain) NSMutableArray *placeName;
#property (nonatomic,retain) IBOutlet UISegmentedControl *segmentedControl;
-(IBAction)refreshButtonPressed:(id)sender;
-(IBAction) segmentedControlIndexChanged;
-(IBAction)SignUpButtonPressed:(id)sender;
-(IBAction)BackButtonPressed:(id)sender;
-(IBAction)AddBeepButtonPressed:(id)sender;
-(id)initWithAnnotation:(id ) annotation;
-(IBAction)sliderChanged:(id)sender;
-(IBAction)MyAccountPageButtonPressed:(id)sender;
-(IBAction)MyBeepsButtonPressed:(id)sender;
#end
.m/
-(void)network:(WNetwork*)network didFinishLoadingWithRequest:(NSInteger)pReq data:(NSMutableDictionary*)pData
{
[self removeLoader];
switch (pReq) {
case JBJsonParser:
{
NSMutableArray *array = [NSMutableArray new];
self.placeName = array;
[array release];
self.placeName = pData;
badgenumber = [placeName count];
NSString *checkstring = [[AppHelper mDataManager] objectForKey:#"numberofbeepsnearby"];
NSInteger check = [checkstring intValue];
switch (check) {
case 0:
{
self.numberofbeeps.text =[NSString stringWithFormat:#"No beeps found nearby. Why not beep something?"];
NSLog(#"%#",checkstring);
}
break;
case 1:
{
self.numberofbeeps.text =[NSString stringWithFormat:#"%# beep found nearby! %d beeps worldwide.",checkstring,badgenumber];
NSLog(#"%#",checkstring);
}
break;
default:
{
self.numberofbeeps.text =[NSString stringWithFormat:#"%# beeps found nearby! %d beeps worldwide.",checkstring,badgenumber];
NSLog(#"%#",checkstring);
}
break;
}
if ([placeName count])
{
for (int i =0; i < [placeName count]; i++)
{
NSDictionary *dict = [placeName objectAtIndex:i];
CLLocationCoordinate2D coordinatemain;
coordinatemain.latitude = [[dict objectForKey:#"Lat"] doubleValue];
coordinatemain.longitude = [[dict objectForKey:#"long"] doubleValue];
DLog(#"id of Beeps %#", mid);
NSString *username = [NSString stringWithFormat:#"by %#",[dict objectForKey:#"username"]];
MyAnnotation *ann = [[MyAnnotation alloc] init];
ann.title = [dict objectForKey:#"beep"];
ann.subtitle = username;
ann.beepid=[dict objectForKey:#"beepid"];
ann.coordinate = coordinatemain;
ann.coordinate.latitude == [[dict objectForKey:#"Lat"] doubleValue];
ann.coordinate.longitude == [[dict objectForKey:#"long"] doubleValue];
[mapView addAnnotation:ann];
[ann release];
}
}
}
break;
default:
break;
}
}
-(IBAction) segmentedControlIndexChanged{
switch (self.segmentedControl.selectedSegmentIndex) {
case 0:
{
Screen1 *objCont = [[Screen1 alloc] initWithNibName:#"Screen1" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
break;
case 1:
{
MapView *objCont = [[MapView alloc] initWithNibName:#"MapView" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
break;
default:
break;
}
}
#pragma mark -
#pragma mark request delegates
-(void)makeAccomodationRequest
{
NSMutableDictionary *paramDic = [[NSMutableDictionary alloc] init];
[self.mWNetowrk makeRequsetWithURL:URL_Showbeepsmap type:JBJsonParser paramDictionary:paramDic delegate:self];
[paramDic autorelease];
}
-(BOOL)network:(WNetwork*)network shouldStartForRequest:(NSInteger)pReq
{
[self addLoaderWithtext:#"Loading"];
return YES;
}
-(void)network:(WNetwork*)network didFailForRequest:(NSInteger)pReq WithError:(NSString*)error
{
[AppHelper showAlert:error];
[self removeLoader];
}
-(void)initializeView
{
[self initializeOutlets];
[self makeAccomodationRequest];
}
-(void)initializeOutlets
{
}
-(IBAction)BackButtonPressed:(id)sender
{
Screen1 *objCont = [[Screen1 alloc] initWithNibName:#"Screen1" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
-(IBAction)refreshButtonPressed:(id)sender
{
MapView *objCont = [[MapView alloc] initWithNibName:#"MapView" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
-(IBAction)MyAccountPageButtonPressed:(id)sender
{
NSString *sid = [[AppHelper mDataManager] objectForKey:#"logout"];
{
NSDecimalNumber *session = [[AppHelper mDataManager] objectForKey:#"sid"];
if ([sid isEqualToString:#"logged out"]||session==NULL) {
AddPlace *objCont = [[AddPlace alloc] initWithNibName:#"AddPlace" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve ;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
else {
MyAccountPage *objCont = [[MyAccountPage alloc] initWithNibName:#"MyAccountPage" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve ;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
}
}
-(IBAction)MyBeepsButtonPressed:(id)sender
{
NSString *sid = [[AppHelper mDataManager] objectForKey:#"logout"];
NSDecimalNumber *session = [[AppHelper mDataManager] objectForKey:#"sid"];
//NSString *sessionStr = [session stringValue];
if ([sid isEqualToString:#"logged out"]||session==NULL) {
[[AppHelper mDataManager] setValue:#"MyBeeps" forKey:#"appflow"];
AddPlace *objCont = [[AddPlace alloc] initWithNibName:#"AddPlace" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve ;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
else {
MyBeeps1 *objCont = [[MyBeeps1 alloc] initWithNibName:#"MyBeeps1" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve ;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
}
-(IBAction)AddBeepButtonPressed:(id)sender
{
NSString *sid = [[AppHelper mDataManager] objectForKey:#"logout"];
NSDecimalNumber *session = [[AppHelper mDataManager] objectForKey:#"sid"];
if([sid isEqualToString:#"logged out"]||session==NULL) {
[[AppHelper mDataManager] setValue:#"Addabeep" forKey:#"appflow"];
AddPlace *objCont = [[AddPlace alloc] initWithNibName:#"AddPlace" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve ;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
else {
[[AppHelper mDataManager] setValue:#"Addabeep" forKey:#"appflow"];
Check20M *objCont = [[Check20M alloc] initWithNibName:#"Check20M" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve ;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
}
#pragma mark -
#pragma mark MKMapViewDelegate
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if (annotation == mapView.userLocation) {
// NSLog(#"nil");
return nil; }
MKPinAnnotationView *pinView = nil;
static NSString *defaultPinID = #"com.invasivecode.pin";
pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if ( pinView == nil )
pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
pinView.pinColor = MKPinAnnotationColorGreen;
pinView.frame=CGRectMake(0, 0, 30, 30);
pinView.canShowCallout = YES;
pinView.animatesDrop = YES;
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
MyAnnotation *temp = (MyAnnotation*)annotation;
infoButton.tag = [temp.beepid integerValue];
[infoButton addTarget:self action:#selector(showDetails:) forControlEvents:UIControlEventTouchUpInside];
pinView.rightCalloutAccessoryView = infoButton;
[defaultPinID release];
return pinView;
}
-(IBAction)showDetails:(id)sender{
UIButton *button = (UIButton*)sender ;
NSLog(#"Annotation Click");
BeepsDetail *objCont = [[BeepsDetail alloc] initWithNibName:#"BeepsDetail" bundle:nil];
objCont.mId = [NSString stringWithFormat:#"%d",button.tag];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
#pragma mark -
#pragma mark mapView delegates
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
mapView.delegate = self;
[self initializeView];
mapView.showsUserLocation = YES;
[self makeAccomodationRequest];
CLLocation *location = [[AppHelper appDelegate] mLatestLocation];
MKCoordinateRegion region;
region.center.latitude = location.coordinate.latitude;
region.center.longitude = location.coordinate.longitude;
region.span.latitudeDelta = 0.001;
// Add a little extra space on the sides
region.span.longitudeDelta = 0.001;
// Add a little extra space on the sides
region = [mapView regionThatFits:region];
[mapView setRegion:region animated:YES];
}
// Listen to change in the userLocation
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.mapView = nil;
self.numberofbeeps =nil;
self.mapView = nil;
self.segmentedControl = nil;
}
- (void)dealloc
{
[mapView release];
// [self.mapView removeFromSuperview];
[placeName release];
//[mid autorelease];
[super dealloc];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use.
}
#end
The following only works on the simulator not on device...
Here is a good procedure for finding bad access errors using zombies. All the tools are built into Xcode.
First change to profiling. Click and hold one the run button.
Now choose zombies. This tool warns you just before you are about to use a deallocated object which would other wise trigger a bad access.
Now when a zombie is detected you will see something like this (minus annotatios!) using the tools you can see the object lifecycle. Double click to be taken the the code.
Hope it helps someone!
I would suggest declaring modal view controllers (objCont) as autorelease as opposed to manually releasing them.

Why doesn't my program enter the viewDidLoad method?

I am trying to test this program on use of Core data. Once again, this is an example from the Dave Marks book. It has four text fields on a view and it loads it by using core data to connect to the database.
The app was created as a window based application and then I added a viewController to it. The file's owner is a sub class of the custom viewController class that I have created.
When I execute it, the UIView comes up with a blank view with no text boxes or labels that I had created in the view.
I put a break point in the main method, it does not even go anywhere from there when I click on step into method button. When I place a break point on the viewDidLoad method, it does not even get to it.
Lastly I do not get any errors on the console. What is going on?
Here is the viewController class:
#import "PersistenceViewController.h"
#import "CoreDataPersistenceAppDelegate.h"
#implementation PersistenceViewController
#synthesize line1;
#synthesize line2;
#synthesize line3;
#synthesize line4;
#pragma mark - View lifecycle
- (void)viewDidLoad
{
CoreDataPersistenceAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:#"Line" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
if (objects == nil) {
NSLog(#"There was an error");
}
for (NSManagedObject *oneObject in objects) {
NSNumber *lineNum = [oneObject valueForKey:#"lineNum"];
NSString *lineText = [oneObject valueForKey:#"lineText"];
NSString *fieldName = [NSString stringWithFormat:#"line%d", [lineNum integerValue]];
UITextField *theField = [self valueForKey:fieldName];
theField.text = lineText;
}
[request release];
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
-(void) applicationWillResignActive:(NSNotification *)notification {
CoreDataPersistenceAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSError *error;
for (int i=1; i<=4; i++) {
NSString *fieldName = [NSString stringWithFormat:#"line%d",i];
UITextField *theField = [self valueForKey:fieldName];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:#"Line" inManagedObjectContext:context];
[request setEntity:entityDescription];
NSPredicate *pred = [NSPredicate predicateWithFormat:#"(lineNum = %d)", i];
[request setPredicate:pred];
NSManagedObject *theLine = nil;
NSArray *objects = [context executeFetchRequest:request error:&error];
if (objects == nil) {
NSLog(#"There was an error");
}
if ([objects count] > 0)
theLine = [objects objectAtIndex:0];
else
theLine = [NSEntityDescription insertNewObjectForEntityForName:#"Line" inManagedObjectContext:context];
[theLine setValue:[NSNumber numberWithInt:i] forKey:#"lineNum"];
[theLine setValue:theField.text forKey:#"lineText"];
[request release];
}
[context save:&error];
}
- (void)viewDidUnload
{
self.line1 = nil;
self.line2 = nil;
self.line3 = nil;
self.line4 = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc
{
[line1 release];
[line2 release];
[line1 release];
[line1 release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#end
Be sure to change the viewcontroller that gets intialized in the appdelegate with the correct nib. The blank UIView is probably the view created when you started the project.
In your AppDelegate there is a method called applicationdidFinishLaunchingWithOptions, in which something like the following code is located:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.viewController = [[RIViewController alloc] initWithNibName:#"RIViewController" bundle:nil];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
In my case I load the RIViewController. By default the nib file has the same name as the controller and is hence named RIViewController aswell.

iphoneSDK: UINavigationController Back button is causing app to crash

My app is crashing when I move between ViewControllers. This is the sequence that causes the crash salesViewController displays confirmViewController. When I press the back button in confirmViewController to go back to salesViewController, the application crashes.
I am not sure why. Here is the code for both of the controllers.
Thanks in advance.
#import "salesViewController.h"
#implementation salesViewController
#synthesize txtCardNumber;
#synthesize txtExpires;
#synthesize txtGrandTotal;
#synthesize txtZip;
#synthesize txtEmail;
#synthesize txtCCV2;
#synthesize txtInvoice;
//#synthesize button;
#synthesize strSaleType;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if(self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
}
return self;
}
-(IBAction)btnTipCalculator:(id)sender
{
NSLog(#"I was pressed");
tipCalcViewController *tipVC = [[tipCalcViewController alloc] initWithNibName:#"tipCalcView" bundle:nil];
tipVC.delegate = self;
tipVC.passedTotal = txtGrandTotal.text;
[self presentModalViewController:tipVC animated:YES];
[tipVC release];
}
-(IBAction)btnDateSelector:(id)sender
{
NSLog(#"I was pressed");
DatePickerViewController *datePickerViewController = [[DatePickerViewController alloc] initWithNibName:#"datePickerView" bundle:nil];
datePickerViewController.delegate = self;
[self presentModalViewController:datePickerViewController animated:YES];
[datePickerViewController release];
}
-(void)datePickerViewController:(DatePickerViewController *)controller didChooseDate:(NSString *)chosenDate{
NSLog(#"Chosen Date as String: %#", chosenDate );
txtExpires.text = chosenDate;
//do processing here... for example let's set the text of the button to the chosen date
//[button setTitle: chosenDate forState: UIControlStateNormal];
[self dismissModalViewControllerAnimated:YES];
}
//callback for modal tipCalculator
-(void)tipCalcViewController:(tipCalcViewController *)controller didChooseTip:(NSString *)chosenTip
{
NSString *strNewTotal = chosenTip;
//close tip calculator
[self dismissModalViewControllerAnimated:YES];
//update GUI
txtGrandTotal.text = strNewTotal;
}
-(void)btnSubmitClicked
{
NSURL *url = [NSURL URLWithString:#"https://www.eProcessingNetwork.Com/cgi-bin/tdbe/transact.pl"];
//NSURL *url = [NSURL URLWithString:#"https://www.eprocessingnetwork.com/Reflect/Post.pl"];
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc]
initWithURL:url] autorelease];
//get settings
//NSUserDefaults *options = [NSUserDefaults standardUserDefaults];
//NSString *acctNumber = [options stringForKey:#"accountNumber"];
//NSString *restrictKey = [options stringForKey:#"restrictKey"];
//uncomment for actual
//[request setPostValue:acctNumber forKey:#"ePNAccount"];
//[request setPostValue:restrictKey forKey:#"RestrictKey"];
if([strSaleType compare:#"Test"] == NSOrderedSame)
{
//FOR TESTING ONLY: UNCOMMENT ABOVE FOR ACTUAL ACCOUNT
[request setPostValue:#"080880" forKey:#"ePNAccount"];
[request setPostValue:#"yFqqXJh9Pqnugfr" forKey:#"RestrictKey"];
}
//FOR TESTING ONLY: UNCOMMENT ABOVE FOR ACTUAL ACCOUNT
[request setPostValue:#"080880" forKey:#"ePNAccount"];
[request setPostValue:#"yFqqXJh9Pqnugfr" forKey:#"RestrictKey"];
//transaction type
if([strSaleType compare:#"Sale"] == NSOrderedSame)
{
[request setPostValue:#"Sale" forKey:#"TranType"];
}
if([strSaleType compare:#"Refund"] == NSOrderedSame)
{
[request setPostValue:#"Return" forKey:#"TranType"];
}
if([strSaleType compare:#"Test"] == NSOrderedSame)
{
[request setPostValue:#"Sale" forKey:#"TranType"];
}
//request no HTML output
[request setPostValue:#"No" forKey:#"HTML"];
//needed to get transID for signature capture
[request setPostValue:#"report" forKey:#"Inv"];
//card number
[request setPostValue:txtCardNumber.text forKey:#"CardNo"];
//parse date
NSString *strDateFull = txtExpires.text;
NSString *strMonth = [strDateFull substringWithRange: NSMakeRange(0, 2)];
NSString *strYear = [strDateFull substringWithRange: NSMakeRange(3, 2)];
//expire month
[request setPostValue:strMonth forKey:#"ExpMonth"];
//expire year
[request setPostValue:strYear forKey:#"ExpYear"];
//total, send as you would write it. no dollar sign needed
[request setPostValue:txtGrandTotal.text forKey:#"Total"];
//address - this makes TBDE ignore requests with no address
[request setPostValue:#"1" forKey:#"SKIP_MISSING"];
//zip
[request setPostValue:txtZip.text forKey:#"Zip"];
//ccv2
[request setPostValue:#"CVV2Type" forKey:#"1"];
[request setPostValue:txtCCV2.text forKey:#"123"];
//email
[request setPostValue:txtEmail.text forKey:#"EMail"];
//invoice # - optional
[request setPostValue:txtInvoice.text forKey:#"Invoice"];
//blocking of course
[request start];
// get confirmation
confirmViewController *anotherViewController = [[confirmViewController alloc] initWithNibName:#"confirmView" bundle:nil];
//set properties
anotherViewController.strConfirmation = [request responseString];
anotherViewController.strCardNumber = txtCardNumber.text;
anotherViewController.strExpires = txtExpires.text;
anotherViewController.strAmount = txtGrandTotal.text;
[self.navigationController pushViewController:anotherViewController animated:YES];
//reset interface
if([anotherViewController.strApproval compare:#"""Y"] == NSOrderedSame)
{
txtCardNumber.text = #"";
txtExpires.text = #"";
txtGrandTotal.text = #"";
txtZip.text = #"";
txtCCV2.text = #"";
txtEmail.text = #"";
txtInvoice.text = #"";
}
[anotherViewController release];
/*
//display the results
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Info"
message:[request responseString]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
[alert release];
*/
}
/*
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
//Needed to get events
[txtCardNumber setDelegate:self];
[txtExpires setDelegate:self];
[txtGrandTotal setDelegate:self];
[txtZip setDelegate:self];
[txtEmail setDelegate:self];
[txtCCV2 setDelegate:self];
[txtInvoice setDelegate:self];
//adjust title depending on sale type
if([strSaleType compare:#"Sale"] == NSOrderedSame)
{
self.title = #"Sales";
NSLog(#"Passed in sale type: %#", strSaleType );
}
if([strSaleType compare:#"Refund"] == NSOrderedSame)
{
self.title = #"Refunds";
NSLog(#"Passed here in sale type: %#", strSaleType );
}
if([strSaleType compare:#"Test"] == NSOrderedSame)
{
self.title = #"Testing";
NSLog(#"Passed in sale type: %#", strSaleType );
}
//add additional button
UIBarButtonItem *submitButton = [[UIBarButtonItem alloc] initWithTitle:#"Submit" style:UIBarButtonItemStylePlain target:self action:#selector(btnSubmitClicked)];
self.navigationItem.rightBarButtonItem = submitButton;
[submitButton release];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
if(txtCardNumber != NULL)
{
[txtCardNumber release];
}
if(txtExpires != NULL)
{
[txtExpires release];
}
if(txtGrandTotal != NULL)
{
[txtGrandTotal release];
}
if(txtZip != NULL)
{
[txtZip release];
}
if(txtEmail != NULL)
{
[txtEmail release];
}
if(txtCCV2 != NULL)
{
[txtCCV2 release];
}
if(txtInvoice != NULL)
{
[txtInvoice release];
}
if(strSaleType != NULL)
{
[strSaleType release];
}
[super dealloc];
}
#end
#import "confirmViewController.h"
#implementation confirmViewController
#synthesize lblStatus;
#synthesize lblCardType;
#synthesize lblCardNumber;
#synthesize lblExpires;
#synthesize lblAmount;
#synthesize lblApproval;
#synthesize strConfirmation;
#synthesize strCardNumber;
#synthesize strExpires;
#synthesize strAmount;
#synthesize strApproval;
-(void)btnSignatureClicked
{
sigCaptureViewController *anotherViewController = [[sigCaptureViewController alloc] initWithNibName:#"sigCaptureView" bundle:nil];
[self.navigationController pushViewController:anotherViewController animated:YES];
[anotherViewController release];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
//prepare confirmation, all that is needed is the first string
NSArray *strings = [strConfirmation componentsSeparatedByString: #","];
NSString *strPreParsed = [strings objectAtIndex:0];
//break out yes/no so we can set status
//NSString *strYesNO = [strPreParsed substringToIndex:2];
NSString *strYesOrNo = [strPreParsed substringWithRange: NSMakeRange(1, 1)];
//save approval for later
strApproval = strYesOrNo;
//debug
NSLog(#"strNo= %#",strYesOrNo);
NSLog(#"strPreParsed= %#", strPreParsed);
//set results
if([strYesOrNo compare:#"Y"] == NSOrderedSame)
{
lblStatus.text = #"Approved";
lblStatus.textColor = [UIColor greenColor];
}
if([strYesOrNo compare:#"N"] == NSOrderedSame)
{
lblStatus.text = #"Declined";
lblStatus.textColor = [UIColor redColor];
}
if([strYesOrNo compare:#"U"] == NSOrderedSame)
{
lblStatus.text = #"Try Again";
lblStatus.textColor = [UIColor redColor];
}
//set card type
if([lblCardNumber.text compare:#"4"] == NSOrderedSame)
{
lblCardType.text = #"Visa";
}
if([lblCardNumber.text compare:#"5"] == NSOrderedSame)
{
lblCardType.text = #"Master";
}
if([lblCardNumber.text compare:#"6"] == NSOrderedSame)
{
lblCardType.text = #"Discover";
}
//set cardnumber
lblCardNumber.text = strCardNumber;
//set expires
lblExpires.text = strExpires;
//set amount
lblAmount.text = strAmount;
//set approval string
lblApproval.text = strPreParsed;
//add signature button
UIBarButtonItem *signatureButton = [[UIBarButtonItem alloc] initWithTitle:#"Signature" style:UIBarButtonItemStylePlain target:self action:#selector(btnSignatureClicked)];
self.navigationItem.rightBarButtonItem = signatureButton;
[signatureButton release];
//set title
self.title = #"Approval";
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
if(lblCardType != NULL)
{
[lblCardType release];
}
if(lblCardNumber != NULL)
{
[lblCardNumber release];
}
if(lblExpires != NULL)
{
[lblExpires release];
}
if(lblAmount != NULL)
{
[lblAmount release];
}
if(lblApproval != NULL)
{
[lblApproval release];
}
if(lblStatus != NULL)
{
[lblStatus release];
}
if(strConfirmation != NULL)
{
[strConfirmation release];
}
if(strCardNumber != NULL)
{
[strCardNumber release];
}
if(strExpires != NULL)
{
[strExpires release];
}
if(strAmount != NULL)
{
[strAmount release];
}
if(strApproval != NULL)
{
[strApproval release];
}
[super dealloc];
}
#end
I think you are releasing properties that should not be released, for instance you create strYesOrNo like this:
NSString *strYesOrNo = [strPreParsed substringWithRange: NSMakeRange(1, 1)];
without allocating the string. So the string belongs to the viewDidLoad function and will be released by this function. But after creating the strYesOrNo you assign it to a class property, like this:
strApproval = strYesOrNo;
By the time you dealloc your viewcontroller you try to release strApproval, but the viewDidLoad allready released this value and you get a bad-access. You can solve this problem by allocating the memory for strApproval like:
strApproval = [[NSString alloc] initWithString:strYesOrNo];
I did not go through all your code so maybe this is also true for some other properties. Hope this helped.