First off, I am a complete noob, so please be gentle when explaining. I have a program that loads a webpage (UIWebview) on the first view controller. The first view controller checks to see if the NSUserDefaults contains "jdoe1234" for the UserName. If it does, it loads the first webpage, if it has something different, it loads a second webpage. I also have an information button that flips to the second view controller.
On the second view controller, a person can type in a username and password and click the Done button which flips them back to the first controller view. Inside the done button code, I am updating the NSUserDefaults to include the username and password textbox values.
My problem is when the person flips back to the first view controller, the webpage is not refreshing with the values that the person just typed in and saved. When I close the program and open it again, the new values show correctly. I have searched and tried different examples, but I am unable to get it to work. I have listed my code below. I appreciate any help on this.
FirstViewController.h
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
#interface FirstViewController : UIViewController {
IBOutlet UIWebView *loadInitialGradebook;
IBOutlet UILabel *labelUserName;
}
- (IBAction)infoButtonPressed:(id)sender;
-(IBAction)refreshWebView;
#property (nonatomic, retain) UILabel *labelUserName;
#end
FirstViewController.m
#import "FirstViewController.h"
#import "SecondViewController.h"
#implementation UACCHViewController
#synthesize labelUserName;
- (IBAction)infoButtonPressed:(id)sender;
{
SecondViewController *second = [[SecondViewController alloc] initWithNibName:nil bundle:nil];
second.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:second animated:YES];
}
- (IBAction)refreshWebView {
[loadInitialWebView reload];
}
// Start Strip URL of spaces & funky characters
- (NSString *)urlEncodeValue:(NSString *)str
{
NSString *result = (NSString *) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)str, NULL, CFSTR("?=&+"), kCFStringEncodingUTF8);
return [result autorelease];
}
// End Strip URL of spaces & funky characters
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
labelUserName.text = [[NSUserDefaults standardUserDefaults] stringForKey:#"txtFieldUserName"];
// Start Load WebView
if (![[NSUserDefaults standardUserDefaults] objectForKey:#"txtFieldUserName"]) {
[loadInitialWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.google.com"]]];
}
else {
NSString *post = [NSString stringWithFormat:#"username=%#&password=%#",[self urlEncodeValue:[[NSUserDefaults standardUserDefaults] stringForKey:#"txtFieldUserName"]],[self urlEncodeValue:[[NSUserDefaults standardUserDefaults] stringForKey:#"txtFieldPassWord"]]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://www.mysite.com/page.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[loadInitialWebView loadRequest: request];
}
// End Load WebView
[super viewDidLoad];
}
#end
SecondViewController.h
#import <UIKit/UIKit.h>
NSUserDefaults *prefs;
#interface SecondViewController : UIViewController {
IBOutlet UITextField *txtUserName;
IBOutlet UITextField *txtPassWord;
}
#property (nonatomic, retain) UITextField *txtUserName;
#property (nonatomic, retain) UITextField *txtPassWord;
#property (nonatomic, retain) NSUserDefaults *prefs;
- (IBAction)doneButtonPressed:(id)sender;
#end
SecondViewController.m
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
#implementation SecondViewController
#synthesize txtUserName;
#synthesize txtPassWord;
#synthesize prefs;
// Start Done Button Pressed
- (IBAction)doneButtonPressed:(id)sender;
{
[self dismissModalViewControllerAnimated:YES];
[prefs setObject:txtUserName.text forKey:#"txtFieldUserName"];
[prefs setObject:txtPassWord.text forKey:#"txtFieldPassWord"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
// End Done Button Pressed
// Start Dismiss the keyboard when a user selects the return key
- (BOOL) textFieldShouldReturn: (UITextField *) theTextField
{
[theTextField resignFirstResponder];
return YES;
}
// End Dismiss the keyboard when a user selects the return key
- (void)viewDidLoad
{
self.prefs = [NSUserDefaults standardUserDefaults];
//Start (Code to set a default username,password)
if (![[NSUserDefaults standardUserDefaults] objectForKey:#"txtFieldUserName"]) {
txtUserName.text = #"jdoe1234";
}
else {
txtUserName.text = [[NSUserDefaults standardUserDefaults] stringForKey:#"txtFieldUserName"];
}
if (![[NSUserDefaults standardUserDefaults] objectForKey:#"txtFieldPassWord"]) {
txtPassWord.text = #"01012011";
}
else {
txtPassWord.text = [[NSUserDefaults standardUserDefaults] stringForKey:#"txtFieldPassWord"];
}
// End (Code to set a default username,password)
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
#end
It probably isn't loading into the first page because the view has already been loaded and isn't being reloaded. You would need to add something to your -viewWillAppear in the first view controller to recheck the NSUserDefaults and load them appropriately.
Related
I wrote a custom class to handle HTTP requests and in result I would like to get an NSString with BODY for next request but when I try to pass this newly created BODY from this object all I get is (null).
But enough words... Let me show you code:
This is ViewController code
#import "ViewController.h"
#import "HTTPRequestHandler.h"
//Definition of constants for URLs which are being used for requests
#define GET_GRANT_KEY_URL #"http://own-dev1.railwaymen.org:4006/api/get_grant_key"
#define PULL_USER_LOCATIONS_URL #"http://own-dev1.railwaymen.org:4006/api/pull_user_locations"
#define ANCHOR_TERMINAL_URL #"http://own-dev1.railwaymen.org:4006/api/anchor_terminal"
//Definition of constants for first request body
#define GRANT_KEY_BODY #"email=vergun#gmail.com&password=password"
#define PULL_USER_LOCATIONS_BODY #"user_id=b6db2184-8b16-433d-ae21-a9a415d9d4dc&grant_key=2aa1d743e7ebc2b5eb7f278f1da62b30d70c1510"
#define ANCHOR_TERMINAL_BODY #"user_id=b6db2184-8b16-433d-ae21-a9a415d9d4dc&grant_key=2aa1d743e7ebc2b5eb7f278f1da62b30d70c1510&location_id=b91d0894-ce90-47dc-b431-4f67252310f2&client_id=2938472398492&client_secret=017305462947509274"
#interface ViewController ()
#property (strong, nonatomic) NSMutableString *resultHTTPBody;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (IBAction)makeRequests {
//First request
HTTPRequestHandler *getGrantKeyRequest = [[HTTPRequestHandler alloc] initWithURL:GET_GRANT_KEY_URL
body:GRANT_KEY_BODY
keysToRecievie:#[#"user_id", #"grant_key"]];
[getGrantKeyRequest makeConnectionWithRequest];
//Second request
HTTPRequestHandler *pullUserLocationsRequest = [[HTTPRequestHandler alloc] initWithURL:PULL_USER_LOCATIONS_URL
body:PULL_USER_LOCATIONS_BODY
keysToRecievie:#[#"location_id"]];
[pullUserLocationsRequest makeConnectionWithRequest];
//Third request
HTTPRequestHandler *anchorTerminalRequest = [[HTTPRequestHandler alloc] initWithURL:ANCHOR_TERMINAL_URL
body:ANCHOR_TERMINAL_BODY
keysToRecievie:#[#"access_token"]];
[anchorTerminalRequest makeConnectionWithRequest];
}
#end
This is .m file from my custrom class
#interface HTTPRequestHandler ()
#property (strong, nonatomic) NSURL *requestURL;
#property (strong, nonatomic) NSData *httpBody;
#property (strong, nonatomic) NSMutableData *responseData;
#property (strong, nonatomic) NSArray *keysToRecieveValues;
#end
#implementation HTTPRequestHandler
- (id)initWithURL:(NSString *)url body:(NSString *)body keysToRecievie:(NSArray *)keys
{
if (self = [super init])
{
self.responseData = [NSMutableData data];
self.requestURL = [[NSURL alloc] initWithString:url];
self.httpBody = [body dataUsingEncoding:NSUTF8StringEncoding];
self.keysToRecieveValues = [[NSArray alloc] initWithArray:keys];
}
return self;
}
- (void)makeConnectionWithRequest
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:self.requestURL];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:self.httpBody];
[NSURLConnection connectionWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[self setRecievedData:[NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:nil]];
NSLog(#"%#", [self createNewBodyWithInitializedKeys]);
}
- (NSString *)createNewBodyWithInitializedKeys
{
NSMutableString *tmpString = [[NSMutableString alloc] init];;
for (NSString *key in self.keysToRecieveValues)
{
[tmpString appendFormat:#"%#=%#?", key, [self.recievedData valueForKey:key]];
}
[tmpString deleteCharactersInRange:NSMakeRange([tmpString length]-1, 1)];
return tmpString;
}
#end
And, finally, header for HTTPRequestHandler:
#import <Foundation/Foundation.h>
#interface HTTPRequestHandler : NSObject
#property (strong, nonatomic) NSDictionary *recievedData;
- (id)initWithURL:(NSString *)url body:(NSString *)body keysToRecievie:(NSArray *)keys;
- (void)makeConnectionWithRequest;
- (NSString *)createNewBodyWithInitializedKeys;
#end
I would be very grateful If you can tell me any hints or show my my mistake.
Ok so I checked your url's responses (hope you don't mind) and it seems that the response is not JSON format, that's why the NSJSONSerialization returns nil, please check your server response and validate it with an online tool or something to make sure it is a JSON format.
EDIT
I know that in xcode 4.4 and above the # synthesise is not needed anymore, but you should anyway add it (just in case) and also, if you declare a property variable you should use it asa a property variable (self.property) unless you are doing some other stuff in the getter method or setter method.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have an existing project that I am adding the CoreData framework to but I'm running into some trouble. I've added CoreData to existing projects before but I'm not sure where I'm going wrong in this case.
I have added all of the necessary code to the AppDelegate.h and .m files. I have added the import statement to my .pch. I've created my data model file with all of the properties of my Lesson object. I've done everything I can think of but when my viewDidLoad method runs through, my managedObjectContext is still nil.
I've posted the code for my AppDelegate and my ViewController below. Hopefully someone can offer some advice regarding where I went wrong. Thank you :)
AppDelegate.h
#import <UIKit/UIKit.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
#end
AppDelegate.m
#import "AppDelegate.h"
#implementation AppDelegate
#synthesize window = _window;
#synthesize managedObjectContext = __managedObjectContext;
#synthesize managedObjectModel = __managedObjectModel;
#synthesize persistentStoreCoordinator = __persistentStoreCoordinator;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
#pragma mark - Core Data stack
// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
if (__managedObjectContext != nil) {
return __managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
__managedObjectContext = [[NSManagedObjectContext alloc] init];
[__managedObjectContext setPersistentStoreCoordinator:coordinator];
}
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 != nil) {
return __managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"iLessonsPiano" 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:#"iLessonsPiano.sqlite"];
NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return __persistentStoreCoordinator;
}
#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 <UIKit/UIKit.h>
#import "Lesson.h"
#import "PDFViewController.h"
#import "MediaPlayer/MediaPlayer.h"
#import "PracticeViewController.h"
#interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
#property (nonatomic, strong) NSManagedObjectContext* managedObjectContext;
// Array to hold all lessons.
#property (nonatomic, strong) NSMutableArray *lessonLibrary;
// Array to hold the purchased lessons.
#property (nonatomic,strong) NSMutableArray *purchasedLessons;
// Lesson detail display items.
#property (strong, nonatomic) IBOutlet UIImageView *coverArt;
#property (weak, nonatomic) IBOutlet UILabel *lessonTitle;
#property (weak, nonatomic) IBOutlet UILabel *lessonSubtitle;
#property (weak, nonatomic) IBOutlet UILabel *timingLabel;
#property (weak, nonatomic) IBOutlet UILabel *keySignatureLabel;
#property (weak, nonatomic) IBOutlet UIImageView *difficultyImage;
#property (weak, nonatomic) IBOutlet UITextView *descriptionTextView;
#property (weak, nonatomic) IBOutlet UIImageView *dividerImage;
#property (weak, nonatomic) IBOutlet UIImageView *detailBackgroundImage;
#property (weak, nonatomic) IBOutlet UIImageView *detailsImage;
#property (strong, nonatomic) IBOutlet UITableView *tableView;
//Table Methods
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
// Variables and Methods for the Video Player
#property (strong, nonatomic) MPMoviePlayerViewController *player;
#end
ViewController.m
#import "ViewController.h"
#import "AppDelegate.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize coverArt;
#synthesize lessonTitle;
#synthesize lessonSubtitle;
#synthesize timingLabel;
#synthesize keySignatureLabel;
#synthesize difficultyImage;
#synthesize descriptionTextView;
#synthesize dividerImage;
#synthesize detailBackgroundImage;
#synthesize detailsImage;
#synthesize purchasedLessons;
#synthesize tableView;
#synthesize player;
#synthesize managedObjectContext;
#synthesize lessonLibrary;
//TABLE METHODS
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return purchasedLessons.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// Create a cell.
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"purchased"];
// Populate the cell with data.
Lesson *temp = [[Lesson alloc] init];
temp = [purchasedLessons objectAtIndex:indexPath.row];
cell.textLabel.text = temp.title;
cell.detailTextLabel.text = temp.subtitle;
// Return the cell.
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Determine what row is selected and retrieve the correct Lesson object.
Lesson *currentSelection = [[Lesson alloc] init];
int row = [indexPath row];
currentSelection = [purchasedLessons objectAtIndex:row];
if (currentSelection.purchaseStatus == 1) {
UIImage *tempCoverArt = [UIImage imageNamed:currentSelection.coverArtFilename];
UIImage *tempDifficulty = [UIImage imageNamed:currentSelection.difficultyImageFilename];
// Change the information in the details pane to the details for the current lesson.
[coverArt setImage:tempCoverArt];
lessonTitle.text = currentSelection.title;
lessonSubtitle.text = currentSelection.subtitle;
timingLabel.text = currentSelection.timing;
keySignatureLabel.text = currentSelection.keySignature;
[difficultyImage setImage:tempDifficulty];
descriptionTextView.text = currentSelection.lessonDescription;
}
}
//END TABLE METHODS
- (void)viewDidLoad
{
[super viewDidLoad];
if (managedObjectContext == nil)
{
managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
}
// Song library
Lesson *Lesson0 = [[Lesson alloc] init];
Lesson0 = [NSEntityDescription insertNewObjectForEntityForName:#"Lesson" inManagedObjectContext:managedObjectContext];
Lesson0.productID = 0;
//Lesson0.purchaseStatus = 1;
Lesson0.title = #"Happy Birthday to You";
Lesson0.subtitle = #"Patty & Mildred Hill";
Lesson0.titleAndSubtitle = #"Happy Birthday to You - Patty & Mildred Hill";
Lesson0.coverArtFilename = #"beethoven.png";
Lesson0.timing = #"3/4";
Lesson0.keySignature = #"G";
Lesson0.difficultyImageFilename = #"easy.png";
Lesson0.lessonDescription = #"Originally, this song piece was called 'Good Morning to All' and was sung to and by children in school.";
Lesson0.sheetFilename = #"1_score";
Lesson0.midiFilename = #"happyBirthdayToYou";
Lesson0.materialsFilename = #"1_score";
Lesson0.roll = #"happyBirthdayToYou";
//Lesson0.startingIndicatorPosition = 175;
Lesson0.rollPositionArray = [NSArray arrayWithObjects: /* 0 */ [NSNumber numberWithInteger:0],
/* 1 */ [NSNumber numberWithInteger:0],
/* 2 */ [NSNumber numberWithInteger:0],
/* 3 */ [NSNumber numberWithInteger:-65],
/* 4 */ [NSNumber numberWithInteger:-100],
/* 5 */ [NSNumber numberWithInteger:-135],
/* 6 */ [NSNumber numberWithInteger:-185],
/* 7 */ [NSNumber numberWithInteger:-185],
/* 8 */ [NSNumber numberWithInteger:-241],
/* 9 */ [NSNumber numberWithInteger:-306],
/* 10 */ [NSNumber numberWithInteger:-341],
/* 11 */ [NSNumber numberWithInteger:-376],
/* 12 */ [NSNumber numberWithInteger:-426],
/* 13 */ [NSNumber numberWithInteger:-426],
/* 14 */ [NSNumber numberWithInteger:-483],
/* 15 */ [NSNumber numberWithInteger:-548],
/* 16 */ [NSNumber numberWithInteger:-582],
/* 17 */ [NSNumber numberWithInteger:-617],
/* 18 */ [NSNumber numberWithInteger:-666],
/* 19 */ [NSNumber numberWithInteger:-701],
/* 20 */ [NSNumber numberWithInteger:-737],
/* 21 */ [NSNumber numberWithInteger:-799],
/* 22 */ [NSNumber numberWithInteger:-834],
/* 23 */ [NSNumber numberWithInteger:-868],
/* 24 */ [NSNumber numberWithInteger:-918],
nil];
// Load in the CoreData library of Lessons
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"Lesson" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *tempArray = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
lessonLibrary = [[NSMutableArray alloc] initWithArray:tempArray];
NSSortDescriptor *desc = [[NSSortDescriptor alloc] initWithKey:#"subtitle" ascending:YES];
[lessonLibrary sortUsingDescriptors:[NSArray arrayWithObjects:desc, nil]];
// Load background images.
UIImage *detailsDivider = [UIImage imageNamed:#"detailsDividerImage.png"];
[dividerImage setImage:detailsDivider];
UIImage *detailsBackground = [UIImage imageNamed:#"detailsBackgroundImage.png"];
[detailBackgroundImage setImage:detailsBackground];
UIImage *detailsPanel = [UIImage imageNamed:#"detailsDisplayImage.png"];
[detailsImage setImage:detailsPanel];
// Load default cover art.
UIImage *defaultCoverArt = [UIImage imageNamed:#"coverArtDefault.png"];
[coverArt setImage:defaultCoverArt];
if (![managedObjectContext save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
for (Lesson *lesson in lessonLibrary) {
[purchasedLessons addObject:lesson];
}
// purchasedLessons = [[NSMutableArray alloc] initWithObjects:Lesson0, nil];
}
- (void)viewDidUnload
{
[self setLessonTitle:nil];
[self setLessonSubtitle:nil];
[self setCoverArt:nil];
[self setTimingLabel:nil];
[self setKeySignatureLabel:nil];
[self setDifficultyImage:nil];
[self setDescriptionTextView:nil];
[self setDividerImage:nil];
[self setDetailBackgroundImage:nil];
[self setDetailsImage:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Segue to the materials screen.
if ([segue.identifier isEqualToString:#"materials"]) {
PDFViewController *pdfViewController = [segue destinationViewController];
NSIndexPath *path = [self.tableView indexPathForSelectedRow];
int row = [path row];
Lesson *selected = [purchasedLessons objectAtIndex:row];
pdfViewController.selectedLesson = selected;
pdfViewController.fileToView = #"materials";
}
// Segue to the sheet screen.
else if ([segue.identifier isEqualToString:#"sheet"]) {
PDFViewController *pdfViewController = [segue destinationViewController];
NSIndexPath *path = [self.tableView indexPathForSelectedRow];
int row = [path row];
Lesson *selected = [purchasedLessons objectAtIndex:row];
pdfViewController.selectedLesson = selected;
pdfViewController.fileToView = #"sheet";
}
// Segue to the practice screen.
else if ([segue.identifier isEqualToString:#"practice"]) {
PracticeViewController *practiceViewController = [segue destinationViewController];
NSIndexPath *path = [self.tableView indexPathForSelectedRow];
int row = [path row];
Lesson *selected = [purchasedLessons objectAtIndex:row];
practiceViewController.selectedLesson = selected;
}
}
#end
Lesson.h
#import <Foundation/Foundation.h>
#interface Lesson : NSObject
#property int purchaseStatus;
#property int productID;
#property (nonatomic, strong) NSString *title;
#property (nonatomic, strong) NSString *subtitle;
#property (nonatomic, strong) NSString *titleAndSubtitle;
#property (nonatomic, strong) NSString *coverArtFilename;
#property (nonatomic, strong) NSString *timing;
#property (nonatomic, strong) NSString *keySignature;
#property (nonatomic, strong) NSString *difficultyImageFilename;
#property (nonatomic, strong) NSString *lessonDescription;
#property (nonatomic, strong) NSString *materialsFilename;
#property (nonatomic, strong) NSString *sheetFilename; // PDF
#property (nonatomic, strong) NSString *midiFilename;
#property (nonatomic, strong) NSString *roll;
#property NSArray *rollPositionArray;
#property int startingIndicatorPosition;
#end
Lesson.m
#import "Lesson.h"
#implementation Lesson
#synthesize productID, coverArtFilename, title, subtitle, titleAndSubtitle, timing, keySignature, difficultyImageFilename, lessonDescription, materialsFilename, sheetFilename, midiFilename, purchaseStatus, roll, rollPositionArray, startingIndicatorPosition;
#end
I'm not sure what happened but I started over and got it to work on the second go around :) It may had had something to do with where my AppDelegate was looking for the model.
I do webservice requests with a UISegmentedControl, when I change segmentedItem and request fast the application crashes with this message:
[Session started at 2011-05-12
10:58:50 +0200.] Terminating in
response to SpringBoard's termination.
[Session started at 2011-05-12
11:06:31 +0200.] GNU gdb
6.3.50-20050815 (Apple version gdb-1516) (Fri Feb 11 06:19:43 UTC
2011) Copyright 2004 Free Software
Foundation, Inc. GDB is free software,
covered by the GNU General Public
License, and you are welcome to change
it and/or distribute copies of it
under certain conditions. Type "show
copying" to see the conditions. There
is absolutely no warranty for GDB.
Type "show warranty" for details. This
GDB was configured as
"--host=i386-apple-darwin
--target=arm-apple-darwin".tty /dev/ttys001 Loading program into
debugger… Program loaded. target
remote-mobile
/tmp/.XcodeGDBRemote-239-58 Switching
to remote-macosx protocol mem 0x1000
0x3fffffff cache mem 0x40000000
0xffffffff none mem 0x00000000 0x0fff
none run Running… [Switching to thread
11779] [Switching to thread 11779]
sharedlibrary apply-load-rules all
continue Program received signal:
“SIGKILL”. warning: Unable to read
symbols for
/Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.3
(8J2)/Symbols/Developer/usr/lib/libXcodeDebuggerSupport.dylib
(file not found). kill quit
The Debugger has exited with status
0.(gdb)
Does anybody have an idea of how can I fix this?
Is this a problem because I'm not using NSOperationQueue?
And if so any suggestions how I can fix this would be very welcomed.
I can not find any memory leaks when running.
Next time I ran it this message got logged:
Program received signal: “EXC_BAD_ACCESS”.
warning: Unable to read symbols for /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.3 (8J2)/Symbols/Developer/usr/lib/libXcodeDebuggerSupport.dylib (file not found).
(gdb)
Here is the code for starting the connection:
Class header ServiceGetChildren:
#import <Foundation/Foundation.h>
#class Authentication;
#class AttendanceReportViewController;
#interface ServiceGetChildren : NSObject {
Authentication *authentication;
AttendanceReportViewController *attendanceReportViewController;
NSString *username;
NSString *password;
NSMutableString *authenticationString;
NSString *encodedLoginData;
NSMutableData *responseData;
NSMutableArray *childrensArray;
}
#property (nonatomic, retain) NSString *username;
#property (nonatomic, retain) NSString *password;
#property (nonatomic, retain) NSMutableString *authenticationString;
#property (nonatomic, retain) NSString *encodedLoginData;
#property (nonatomic, retain) NSMutableData *responseData;
#property (nonatomic, retain) NSMutableArray *childrensArray;
- (void)startService:(NSURL *)url :(NSString *)method withParent:(UIViewController *)controller;
#end
Class handling the request:
#import "ServiceGetChildren.h"
#import "JSON.h"
#import "Base64.h"
#import "AttendanceReportViewController.h"
#import "Authentication.h"
#implementation ServiceGetChildren
#synthesize appDelegate;
#synthesize username;
#synthesize password;
#synthesize authenticationString;
#synthesize encodedLoginData;
#synthesize responseData;
#synthesize childrensArray;
- (id) init {
if ((self = [super init])) {
}
return self;
}
- (void)startService:(NSURL *)url :(NSString *)method withParent:(UIViewController *)controller {
username = appDelegate.username;
password = appDelegate.password;
attendanceReportViewController = (AttendanceReportViewController *)controller;
Authentication *auth = [[Authentication alloc] init];
authenticationString = (NSMutableString*)[#"" stringByAppendingFormat:#"%#:%#", username, password];
encodedLoginData = [auth encodedAuthentication:authenticationString];
[auth release];
// Setup up the request with the url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
cachePolicy: NSURLRequestReloadIgnoringCacheData
timeoutInterval: 20.0];
[request setHTTPMethod:method];
[request setValue:[NSString stringWithFormat:#"Basic %#", encodedLoginData] forHTTPHeaderField:#"Authorization"];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
// Display the network indicator when the connection request started
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
// Check that the NSURLConnection was successful and then initialize the responseData
if(connection) {
NSLog(#"Connection made");
responseData = [[NSMutableData data] retain];
}
else {
NSLog(#"Connection could not be made");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"Connection finished loading.");
// Dismiss the network indicator when connection finished loading
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
// Parse the responseData of json objects retrieved from the service
SBJSON *parser = [[SBJSON alloc] init];
NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *jsonData = [parser objectWithString:jsonString error:nil];
NSMutableArray *array = [jsonData objectForKey:#"Children"];
childrensArray = [NSMutableArray arrayWithArray:array];
// Callback to AttendanceReportViewController that the responseData finished loading
[attendanceReportViewController loadChildren];
[connection release];
[responseData release];
[jsonString release];
[parser release];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Connection failure.");
NSLog(#"ERROR%#", error);
// Dismiss the network indicator when connection failure occurred
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[connection release];
// Inform the user that the server was unavailable
}
- (void) dealloc {
[attendanceReportViewController release];
[super dealloc];
}
Class header for AttendanceReportViewController:
#import <UIKit/UIKit.h>
#class ServiceGetGroups;
#class ServiceGetChildren;
#class DetailViewController;
#interface AttendanceReportViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> {
ServiceGetGroups *serviceGetGroups;
ServiceGetChildren *serviceGetChildren;
DetailViewController *detailViewController;
UISegmentedControl *segmentedControl;
IBOutlet UIToolbar *groupsToolbar;
NSMutableArray *btnArray;
NSInteger index;
IBOutlet UITableView *theTableView;
IBOutlet UILabel *attendanceLabel;
IBOutlet UILabel *abscentLabel;
IBOutlet UILabel *totalLabel;
NSMutableDictionary *selectRequestDictionary;
NSMutableDictionary *selectNameDictionary;
NSMutableArray *groupsArray;
NSMutableArray *childrensArray;
NSDictionary *childrensDictionary;
NSURL *url;
}
#property (nonatomic, retain) ServiceGetGroups *serviceGetGroups;
#property (nonatomic, retain) ServiceGetChildren *serviceGetChildren;
#property (nonatomic, retain) DetailViewController *detailViewController;
#property (nonatomic, retain) IBOutlet UIToolbar *groupsToolbar;
#property (nonatomic, retain) IBOutlet UITableView *theTableView;
#property (nonatomic, retain) IBOutlet UILabel *attendanceLabel;
#property (nonatomic, retain) IBOutlet UILabel *abscentLabel;
#property (nonatomic, retain) IBOutlet UILabel *totalLabel;
#property (nonatomic, retain) UISegmentedControl *segmentedControl;
#property (nonatomic) NSInteger index;
#property (nonatomic, retain) NSMutableArray *btnArray;
#property (nonatomic, retain) NSMutableDictionary *selectRequestDictionary;
#property (nonatomic, retain) NSMutableDictionary *selectNameDictionary;
#property (nonatomic, retain) NSMutableArray *groupsArray;
#property (nonatomic, retain) NSMutableArray *childrensArray;
#property (nonatomic, retain) NSDictionary *childrensDictionary;
#property (nonatomic, retain) NSURL *url;
- (void)setupSegmentedControl;
- (void)requestGroups;
- (void)requestChildren:(NSNumber *)groupId;
- (void)loadGroups;
- (void)loadChildren;
#end
Class that the Uses the UISegmentedControl:
#import "JSON.h"
#import "AttendanceReportViewController.h"
#import "CustomCellViewController.h"
#import "DetailViewController.h"
#import "ServiceGetGroups.h"
#import "ServiceGetChildren.h"
#import "Group.h"
#import "Child.h"
#implementation AttendanceReportViewController
#synthesize serviceGetGroups;
#synthesize serviceGetChildren;
#synthesize detailViewController;
#synthesize segmentedControl;
#synthesize groupsToolbar;
#synthesize index;
#synthesize btnArray;
#synthesize theTableView;
#synthesize attendanceLabel;
#synthesize abscentLabel;
#synthesize totalLabel;
#synthesize selectRequestDictionary;
#synthesize selectNameDictionary;
#synthesize groupsArray;
#synthesize childrensArray;
#synthesize childrensDictionary;
#synthesize url;
#pragma mark -
#pragma mark View lifecycle
// 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 {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
}
return self;
}
- (void)requestGroups {
NSURL *groupsURL = [NSURL URLWithString:#"http://services/groups"];
[serviceGetGroups startService:groupsURL :#"GET" withParent:self];
}
- (void)requestChildren:(NSNumber *)groupId {
NSLog(#"%#", groupId);
NSString *baseURL = #"http://services/group/";
NSString *method = [NSString stringWithFormat:#"%#%#", groupId, #"/children"];
NSString *theURL = [NSString stringWithFormat:#"%#%#", baseURL, method];
self.url = [NSURL URLWithString:theURL];
NSLog(#"%#", self.url);
[serviceGetChildren startService:self.url :#"GET" withParent:self];
}
- (void)loadGroups {
// Retrieve a array with dictionaries of groups from ServiceGetGroups
self.groupsArray = [[serviceGetGroups.groupsArray copy] autorelease];
// The array to hold segmentedItems for the segmentedControl, representing groups buttons
btnArray = [NSMutableArray arrayWithObjects: #"Alla", nil];
for (NSDictionary *groupDict in groupsArray) {
// Add each groups name to the btnArray as segmentedItems for the segmentedControl
[btnArray addObject:[groupDict objectForKey:#"Name"]];
}
// Create a new NSMutableDictionary with group names as keys and group id´s as values
// used for reference to segementedControl items to make request to serviceGetChildren
self.selectRequestDictionary = [NSMutableDictionary dictionary];
for (NSDictionary *dict in groupsArray) {
[selectRequestDictionary setObject:[dict objectForKey:#"Id"] forKey:[dict objectForKey:#"Name"]];
}
// Create a new NSMutableDictionary with group id´s as keys and group names as values
// used for retrieving a groupName from a passed id
self.selectNameDictionary = [NSMutableDictionary dictionary];
for (NSDictionary *dict in groupsArray) {
[selectNameDictionary setObject:[dict objectForKey:#"Name"] forKey:[dict objectForKey:#"Id"]];
}
[self setupSegmentedControl];
}
- (void)setupSegmentedControl {
// Setup the UISegmentedControl as groups buttons
segmentedControl = nil;
segmentedControl = [[UISegmentedControl alloc] initWithItems:btnArray];
segmentedControl.tintColor = [UIColor darkGrayColor];
segmentedControl.selectedSegmentIndex = 0;
segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth;
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.frame = CGRectMake(0, 0, 300, 30);
// Setup the target and actions for the segmentedControl
[segmentedControl addTarget:self
action:#selector(selectGroup:)
forControlEvents:UIControlEventValueChanged];
// Add the UISegmentedControl as a UIBarButtonItem subview to the UIToolbar
UIBarButtonItem *segmentedItem = [[[UIBarButtonItem alloc] initWithCustomView:segmentedControl] autorelease];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
NSArray *groupsButtons = [NSArray arrayWithObjects:flexSpace, segmentedItem, flexSpace, nil];
[groupsToolbar setItems:groupsButtons];
[flexSpace release];
}
- (void)loadChildren {
// Retrieve a array with dictionaries of children from ServiceGetChildren
self.childrensArray = [[serviceGetChildren.childrensArray copy] autorelease];
// TODO create seperate method - Setup compilation bar values
int total = [childrensArray count];
totalLabel.text = [NSString stringWithFormat:#"%d", total];
[theTableView reloadData];
}
// Handles UIControlEventValueChanged for UISegmentedControl, retreives the name and id for a selected group
- (void)selectGroup:(UISegmentedControl *)theSegmentedControl {
NSString *selectedGroup = [segmentedControl titleForSegmentAtIndex: [segmentedControl selectedSegmentIndex]];
NSNumber *selectedId = [selectRequestDictionary objectForKey:selectedGroup];
// Persist the selectedSegmentIndex when view switches to detaildView
index = [segmentedControl selectedSegmentIndex];
// Request children based on the selected groupId
[self requestChildren:selectedId];
}
- (void)viewDidLoad {
[self requestGroups];
[super viewDidLoad];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
//self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [childrensArray count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"CustomCell";
// Load from nib
CustomCellViewController *cell = (CustomCellViewController *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle]
loadNibNamed:#"CustomCellView"
owner:nil
options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[UITableViewCell class]]) {
cell = (CustomCellViewController *) currentObject;
break;
}
}
}
// Set up a children dictionary for easy retrieving specific values to display in the UITableView
childrensDictionary = [childrensArray objectAtIndex:indexPath.row];
NSNumber *idForName = [childrensDictionary valueForKey:#"GroupId"];
NSString *name = [NSString stringWithFormat:#"%# %#",
[childrensDictionary valueForKey:#"Firstname"],
[childrensDictionary valueForKey:#"Surname"]];
NSString *group = [NSString stringWithFormat:#"%#",
[selectNameDictionary objectForKey:idForName]];
cell.childNameLabel.text = name;
cell.groupNameLabel.text = group;
cell.scheduleLabel.text = #"Schema";
cell.deviationLabel.text = #"Avvikelse";
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here. Create and push the detailedViewController.
if (detailViewController == nil) {
DetailViewController *_detailViewcontroller = [[DetailViewController alloc]
initWithNibName:#"DetailView" bundle:nil];
self.detailViewController = _detailViewcontroller;
[_detailViewcontroller release];
}
childrensDictionary = [childrensArray objectAtIndex:indexPath.row];
NSNumber *idForName = [childrensDictionary valueForKey:#"GroupId"];
NSString *group = [NSString stringWithFormat:#"%#",
[selectNameDictionary objectForKey:idForName]];
[self.detailViewController initWithDetailsSelected:childrensDictionary:group];
[self.navigationController pushViewController:detailViewController animated:YES];
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
segmentedControl = nil;
}
- (void)dealloc {
[segmentedControl release];
[groupsArray release];
[childrensArray release];
[detailViewController release];
[super dealloc];
}
#end
OK here we go. First of all, I could not test the code, so I need your feedback.
The main problem with this class is, you only have one instance, which you reuse every time you hit the segmented control. This leads to creation of new instances of the NSURLConnection. So let's correct a bit in the header. I changed the NSString properties to copy. Have a look at this Q&A to know why, however this is not important for the improvement, just wanted to let you know.
I've removed Authentication *authentication; looked like you don't use it.
Added NSURLConnection as property so we keep a reference on it.
Header file
#class Authentication;
#class AttendanceReportViewController;
#interface ServiceGetChildren : NSObject {
AttendanceReportViewController *attendanceReportViewController;
NSString *username;
NSString *password;
NSMutableString *authenticationString;
NSString *encodedLoginData;
NSMutableData *responseData;
NSMutableArray *childrensArray;
NSURLConnection *connection;
}
#property (nonatomic, copy) NSString *username;
#property (nonatomic, copy) NSString *password;
#property (nonatomic, retain) NSMutableString *authenticationString;
#property (nonatomic, copy) NSString *encodedLoginData;
#property (nonatomic, retain) NSMutableData *responseData;
#property (nonatomic, retain) NSMutableArray *childrensArray;
#property (nonatomic, retain) NSURLConnection *connection
- (void)startService:(NSURL *)url :(NSString *)method withParent:(UIViewController *)controller;
#end
Next comes the Implementation file. I only altered the startService method and dealloc.
If you declare properties, use them :) Have a look at this Q&A for some explanations on synthesized properties.
Always release what you own, so I added release code in the dealloc.
Cancel the previous request!!! If there is none, the message is sent to nil, which causes no harm.
Implementation file
- (void)startService:(NSURL *)url:(NSString *)method withParent:(UIViewController *)controller
{
self.username = appDelegate.username;
self.password = appDelegate.password;
[connection cancel];
attendanceReportViewController = (AttendanceReportViewController *)controller;
Authentication *auth = [[Authentication alloc] init];
authenticationString = (NSMutableString *)[#"" stringByAppendingFormat:#"%#:%#", username, password];
self.encodedLoginData = [auth encodedAuthentication:authenticationString];
[auth release];
// Setup up the request with the url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:20.0];
[request setHTTPMethod:method];
[request setValue:[NSString stringWithFormat:#"Basic %#", encodedLoginData] forHTTPHeaderField:#"Authorization"];
self.connection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
// Display the network indicator when the connection request started
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
// Check that the NSURLConnection was successful and then initialize the responseData
if (connection) {
NSLog(#"Connection made");
self.responseData = [NSMutableData data];
} else {
NSLog(#"Connection could not be made");
}
}
...
- (void) dealloc
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[connection cancel];
[connection release];
[appDelegate release];
[responseData release];
[username release];
[password release];
[authenticationString release];
[encodedLoginData release];
[responseData release];
[childrensArray release];
[super dealloc];
}
Hope this helps for the next steps. However I think we will have to work a bit on the solution until it's final.
I have spent hours trying to get my project working and I just can't get it working.
Basically, I'm trying to use NSUserDefaults to save a custom object when the user hits a save button and load all the data up when the app loads. If there is no previous NSUserDefault saved, I want to set some defaults. In the end, I am getting EXC_BAD_ACCESS when trying to load a previously-saved NSUserDefault. It works fine the first load, when setting the starting data. And the thing is, when I try to enable NSZombieEnabled and the other env vars for it, it somehow loads fine without the EXC_BAD_ACCESS. So here's what I'm working with:
[App Delegate.h]
#import <UIKit/UIKit.h>
#import "Note.h"
#interface ToDoWallAppDelegate : NSObject <UIApplicationDelegate> {
...
Note *note;
}
...
#property (retain) Note *note;
#end
[App Delegate.m]
- (void)applicationDidFinishLaunching:(UIApplication *)application {
...
note = [[Note alloc] init];
NSUserDefaults *stdDefaults = [NSUserDefaults standardUserDefaults];
NSData *noteData = [stdDefaults objectForKey:#"Note"];
if (noteData) {
self.note = (Note *)[NSKeyedUnarchiver unarchiveObjectWithData:noteData];
} else {
note.background = [UIImage imageNamed:#"Cork.jpg"];
note.picture = [UIImage imageNamed:#"Cork.jpg"];
note.font = [UIFont fontWithName:#"Helvetica" size:18.0f];
note.fontColor = [UIColor blackColor];
note.fontNameIndex = 9;
note.fontSizeIndex = 6;
note.fontColorIndex = 0;
note.backgroundIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
note.pictureIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
note.text = #"Type note here...";
}
...
}
- (void)dealloc {
...
[note release];
[super dealloc];
}
[View Controller]
- (void)saveNote {
...
NSUserDefaults *stdDefaults = [NSUserDefaults standardUserDefaults];
if (stdDefaults) {
NSData *noteData = [NSKeyedArchiver archivedDataWithRootObject:UIAppDelegate.note];
[stdDefaults setObject:noteData forKey:#"Note"];
[stdDefaults synchronize];
}
}
[Note.h]
#import <Foundation/Foundation.h>
#interface Note : NSObject <NSCoding> {
UIImage *background, *picture;
UIFont *font;
UIColor *fontColor;
int fontNameIndex, fontSizeIndex, fontColorIndex;
NSIndexPath *backgroundIndexPath, *pictureIndexPath;
BOOL customBackground;
NSString *text;
}
#property (retain) UIImage *background, *picture;
#property (retain) UIFont *font;
#property (retain) UIColor *fontColor;
#property int fontNameIndex, fontSizeIndex, fontColorIndex;
#property (retain) NSIndexPath *backgroundIndexPath, *pictureIndexPath;
#property BOOL customBackground;
#property (retain) NSString *text;
- (Note *)init;
#end
[Note.m]
#import "Note.h"
#implementation Note
#synthesize background, picture, font, fontColor, fontNameIndex, fontSizeIndex, fontColorIndex, customBackground, backgroundIndexPath, pictureIndexPath, text;
- (Note *)init {
if (self = [super init]) {
background = [[UIImage alloc] init];
picture = [[UIImage alloc] init];
font = [[UIFont alloc] init];
fontColor = [[UIColor alloc] init];
backgroundIndexPath = [[NSIndexPath alloc] init];
pictureIndexPath = [[NSIndexPath alloc] init];
text = [[NSString alloc] init];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
NSData *dataBackground = UIImagePNGRepresentation(background);
NSData *dataPicture = UIImagePNGRepresentation(picture);
[encoder encodeObject:dataBackground forKey:#"dataBackground"];
[encoder encodeObject:dataPicture forKey:#"dataPicture"];
[encoder encodeObject:font forKey:#"font"];
[encoder encodeObject:fontColor forKey:#"fontColor"];
[encoder encodeInt:fontSizeIndex forKey:#"fontSizeIndex"];
[encoder encodeInt:fontColorIndex forKey:#"fontColorIndex"];
[encoder encodeBool:customBackground forKey:#"customBackground"];
[encoder encodeObject:backgroundIndexPath forKey:#"backgroundIndexPath"];
[encoder encodeObject:pictureIndexPath forKey:#"pictureIndexPath"];
[encoder encodeObject:text forKey:#"text"];
}
- (Note *)initWithCoder:(NSCoder *)decoder {
if (self = [super init]) {
NSData *dataBackground = [decoder decodeObjectForKey:#"dataBackground"];
NSData *dataPicture = [decoder decodeObjectForKey:#"dataPicture"];
background = [[UIImage imageWithData:dataBackground] retain];
picture = [[UIImage imageWithData:dataPicture] retain];
font = [[decoder decodeObjectForKey:#"font"] retain];
fontColor = [[decoder decodeObjectForKey:#"fontColor"] retain];
fontNameIndex = [decoder decodeIntForKey:#"fontNameIndex"];
fontColorIndex = [decoder decodeIntForKey:#"fontColorIndex"];
customBackground = [decoder decodeBoolForKey:#"customBackground"];
backgroundIndexPath = [[decoder decodeObjectForKey:#"backgroundIndexPath"] retain];
text = [[decoder decodeObjectForKey:#"text"] retain];
}
return self;
}
- (void)dealloc {
[super dealloc];
[background release];
[picture release];
[font release];
[fontColor release];
[backgroundIndexPath release];
[pictureIndexPath release];
[text release];
}
#end
I really need some help I appreciate it.
Edit:
Btw, there are also lines from other files that edit the App Delegate's Note object, such as:
#define UIAppDelegate ((ToDoWallAppDelegate *)[UIApplication sharedApplication].delegate)
...
UIAppDelegate.note.backgroundIndexPath = indexPath;
Edit:
This is what debugger wrote:
#0 0x90be9ed7 in objc_msgSend
#1 0x03b05210 in ??
#2 0x000023ce in -[ToDoWallAppDelegate setNote:] at ToDoWallAppDelegate.m:14
#3 0x00002216 in -[ToDoWallAppDelegate applicationDidFinishLaunching:] at ToDoWallAppDelegate.m:35
Which are:
note.text = #"Type note here...";
//and
#synthesize window, note;
I'm not sure if this is what's causing your problem, but I believe that [super dealloc] should be the LAST line of your dealloc method, not the first.
Have a look at documentation how to setup defaults
Using NSUserDefaults
If you need more info have a look in Hillega's book "Cocoa programming for Mac OS X" bignerdranch.com/books, it's explained there.
You should consider changing the headline to "How to use NSUserDefaults" ...
Example how to setup default value, in your class in initialize put something like:
+ (void)initialize{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *appDefaults = [NSDictionary
dictionaryWithObject:#"YES" forKey:#"DeleteBackup"];
[defaults registerDefaults:appDefaults];
}
You could post where exactly are you getting the error instead of posting the whole code. Run it through debugger and see where it stops.
i have integrated Fbconnect in LoginViewController.I want to logout the session from another view controller .. How i can do this ?
I tried this ..
LoginViewController *obj1 = [[LoginViewController alloc] init];
[obj1._session logout];
[obj1._session.delegates removeObject: self];
It removing the session..But wen i go to LoginViewController the button is showing logout.But when i quit application and run it, the image is updated.
In LoginViewController i have
#interface LoginViewController : UIViewController <FBDialogDelegate, FBSessionDelegate, FBRequestDelegate>{
IBOutlet UITextField *txtUsername;
IBOutlet UITextField *txtPassword;
IBOutlet UILabel *lblMessage;
IBOutlet FBLoginButton* _loginButton;
FBSession* _session;
}
#property (nonatomic, retain) FBSession *_session;
and am synthesizing it #synthesize _session;
....What else i have to do ?
Somebody please help me..am very new to Iphone application and objective c
I got the answer ..My Friend helped me.. i want to share it...
simply
import "FBConnect.h"
in ur second view controller
then .......
FBSession *session = [FBSession
session]; [session logout];
It works fine
-(void)clickfb:(id)sender
{
NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie* cookie in
[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
[cookies deleteCookie:cookie];
}
[self showLoggedOut:YES];
}
(void) showLoggedOut:(BOOL)clearInfo {
//[self.navigationController setNavigationBarHidden:YES animated:NO];
// // Remove saved authorization information if it exists and it is
// // ok to clear it (logout, session invalid, app unauthorized)
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (clearInfo && [defaults objectForKey:#"FBAccessTokenKey"]) {
[defaults removeObjectForKey:#"FBAccessTokenKey"];
[defaults removeObjectForKey:#"FBExpirationDateKey"];
[defaults synchronize];
//
// // Nil out the session variables to prevent
// // the app from thinking there is a valid session
AppDelegate *delegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
if (nil != [[delegate facebook] accessToken]) {
[delegate facebook].accessToken = nil;
}
if (nil != [[delegate facebook] expirationDate]) {
[delegate facebook].expirationDate = nil;
}
}
}