iPhone -trouble with a loading data from webservice into a tableview - iphone

I am using a Window based application and then loading up my initial navigationview based controller in the appDelegate part - application didFinishLaunchingwithOptions (UPDATED)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];
return YES;
}
The method of getting the data from the webservice is usually triggered in this method of viewdidload .... in the [self getData]; method.
- (void)viewDidLoad
{
[super viewDidLoad];
if (_refreshHeaderView == nil) {
EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.tableView.bounds.size.height, self.view.frame.size.width, self.tableView.bounds.size.height)];
view.delegate = self;
[self.tableView addSubview:view];
_refreshHeaderView = view;
[view release];
}
// update the last update date
[_refreshHeaderView refreshLastUpdatedDate];
[self loadImages];
HUDMB = [[MBProgressHUD alloc] initWithView:self.view];
[self.view addSubview:HUDMB];
HUDMB.dimBackground = YES;
// Regiser for HUD callbacks so we can remove it from the window at the right time
HUDMB.delegate = self;
HUDMB.labelText = #"Loading..";
[HUDMB show:TRUE];
[self getData];
[self.tableView reloadData];
}
Before loading it if the user is not registered/ does not have a credentials present then it takes the user to a login view controller .
- (void)loadView {
[super loadView];
if([Preferences isValid]?YES:NO)
{
}
else
{
int r = arc4random() % 5;
switch (r) {
case 0:
{
loginViewController *sampleView = [[loginViewController alloc] initWithNibName:#"loginViewController" bundle:nil];
[self.navigationController presentModalViewController:sampleView animated:YES];
[sampleView release];
}
break;
case 1:
{
loginViewController *sampleView = [[loginViewController alloc] initWithNibName:#"loginViewController" bundle:nil];
[sampleView setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
[self.navigationController presentModalViewController:sampleView animated:YES];
[sampleView release];
}
break;
case 2:
{
loginViewController *sampleView = [[loginViewController alloc] initWithNibName:#"loginViewController" bundle:nil];
[sampleView setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
[self.navigationController presentModalViewController:sampleView animated:YES];
[sampleView release];
}
break;
case 4:
{
loginViewController *sampleView = [[loginViewController alloc] initWithNibName:#"loginViewController" bundle:nil];
[sampleView setModalTransitionStyle:UIModalTransitionStylePartialCurl];
[self.navigationController presentModalViewController:sampleView animated:YES];
[sampleView release];
}
break;
case 3:
{
loginViewController *sampleView = [[loginViewController alloc] initWithNibName:#"loginViewController" bundle:nil];
[sampleView setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
[self.navigationController presentModalViewController:sampleView animated:YES];
[sampleView release];
}
break;
default:
break;
}
}
}
I think the getdata function is making a lot of troubles. so let me add that and also the corresponding functions i use for data retrieval and serialization.
-(void)getData{
NSLog(#"loggin into call sheet page");
[self getCallSheetData];
NSLog(#"after call sheet");
}
- (void)getCallSheetData
{
NSString *postCMD = #"Blah... Blah... Blah...";
NSMutableData *postDataCMD = (NSMutableData *)[postCMD dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSURL *url = [NSURL URLWithString:[Preferences getURL]];
// NSLog(#"get call Sheet");
NSString *postLengthCMD = [NSString stringWithFormat:#"%d", [postDataCMD length]+1];
// NSLog(#"The CS String: %#",[Preferences retriveSession]);
requestCMD = [ASIHTTPRequest requestWithURL:url];
[requestCMD setURL:url];
[requestCMD addRequestHeader:#"Content-Length" value:postLengthCMD];
[requestCMD addRequestHeader:#"Content-Type" value:#"application/x-www-form-urlencoded"];
[requestCMD addRequestHeader:#"user-Agent" value:#"Mobile 1.4" ];
[requestCMD addRequestHeader:#"Content-Language" value:#"en-US"];
[requestCMD addRequestHeader:#"Accept-Encoding" value:#"gzip"];
[requestCMD addRequestHeader:#"Cookie" value:[Preferences retriveSession]];
[requestCMD setPostBody:postDataCMD];
[requestCMD setDelegate:self];
[requestCMD startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSMutableArray *CSArray = [[NSMutableArray alloc] init];
if( [[request responseString] isEqualToString:#"OK"]){
return;
}
// Use when fetching binary data
NSData *responseData = [request responseData];
NSDateFormatter *formatter1=[[NSDateFormatter alloc]init];
[formatter1 setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
[formatter1 setTimeZone:gmt];
NSDateFormatter *formatterFinal=[[NSDateFormatter alloc]init];
[formatterFinal setDateStyle:NSDateFormatterMediumStyle];
[formatterFinal setTimeStyle: NSDateFormatterShortStyle];
[formatterFinal setLocale:[NSLocale currentLocale]];
JSONDecoder *jCSArray = [[JSONDecoder alloc]init];
NSMutableArray *theObject = [jCSArray objectWithData:responseData];
// CallSheet= [NSMutableArray arrayWithCapacity:50];
for(id key in theObject)
{
csr = [[CallSheetRecord alloc] init];
// cName,cCompany,cId,cMemberId,crcStatus,crcTarget,cImportance,cLastContact
csr.importance = #"1";
csr.rcstatus = #"1";
csr.rcTarget = #"1";
csr.company = #"";
csr.lastContact= #"";
if([key valueForKey:#"firstName"] != Nil)
{
csr.name = [NSString stringWithFormat:#"%#",[key valueForKey:#"firstName"]] ;
if ([key valueForKey:#"lastName"] != Nil) {
csr.name = [csr.name stringByAppendingString:#" "];
csr.name = [csr.name stringByAppendingString:[NSString stringWithFormat:#"%#",[key valueForKey:#"lastName"]]];
}
}
if([key valueForKey:#"company"] != Nil)
{
csr.company = [NSString stringWithFormat:#"%#",[key valueForKey:#"company"]] ;
}
if([key valueForKey:#"memberId"] != Nil)
{
csr.memberId = [NSString stringWithFormat:#"%#",[key valueForKey:#"memberId"]] ;
}
if([key valueForKey:#"id"] != Nil)
{
csr.id_ = [NSString stringWithFormat:#"%#",[key valueForKey:#"id"]] ;
}
if([key valueForKey:#"lastContact"] != Nil)
{
NSDate *finalDate =[formatter1 dateFromString:[NSString stringWithFormat:#"%#",[key valueForKey:#"lastContact"]]];
//NSString *timeStamp = [formatter1 stringFromDate:[finalDate descriptionWithLocale:[NSLocale currentLocale]]];
//NSLog(#"Time stamp : %#",[finalDate descriptionWithLocale:[NSLocale currentLocale]]);
//NSLog(#"Time stamp : %#",timeStamp);
//csr.lastContact = [key valueForKey:#"lastContact"];
csr.lastContact = [formatterFinal stringFromDate:finalDate];
}
if([key valueForKey:#"importance"] != Nil)
{
csr.importance = [NSString stringWithFormat:#"%#",[key valueForKey:#"importance"]];
}
if([key valueForKey:#"rcStatus"] != Nil)
{
csr.rcstatus= [NSString stringWithFormat:#"%#",[key valueForKey:#"rcStatus"]] ;
}
if([key valueForKey:#"rcTarget"] != Nil)
{
csr.rcTarget = [NSString stringWithFormat:#"%#",[key valueForKey:#"rcTarget"]] ;
}
[CSArray addObject:csr];
}
CSD = [CSArray mutableCopy];
[CSArray release];
[formatter1 release];
[formatterFinal release];
//CallSheetArray = [CSArray mutableCopy];
//[csr release];
[jCSArray release];
[HUDMB hide:TRUE];
[self.tableView reloadData];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
UIAlertView *message = [[[UIAlertView alloc] initWithTitle:#"Hello World!"
message:[NSString stringWithFormat:#"%#",error]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil]autorelease];
[message show];
}
then right after that i try to load the table with [self getData]; that i get make using webservice call using asiHTTP .. for this question lets say it takes 3 seconds time to get the data and then deserialize it . now... my question is it works out okey in the later runs as I store the username and password in a seure location... but in the first instance.... i am not able to get the data to laod to the tableview... I have tried a lot of things...
1. Initially the data fetch methods was in a diffrent methods.. so i thought that might be the problem as then moved it the same place as the tbleviewController(navigationController)
2. I event put in the Reload data at the end of the functionality for the data parsing and deserialization... nothing happens.
3. The screen is black screen with nothing displayed on it for a good 5 seconds in the consecutive launches of the app.... so could we have something like a MBPorgressHUD implemented for the same.
could any one please help for these scenarios and guidance as to what paths to take from here. ...
Update:
Bounty Just answer 2 of the questions the best you can... The property was a thing i tried but it did not work... but my problem is not that... my problem is my screen is not able to load data from a webservice after i login until i do the "pull to refresh". Next eventualy starting my app takes about 5 seconds to show the screen(till that it shows a black screen)... what is the best way to show the apps Blank screen to the End- user when they make it to the app. I dont want the user to think the app is not working or has adversly affected their phone.

There are a number of potential issues here. The first is related to [self getData] - is this blocking or not?
1. getData is blocking (synchronous)
If this method is blocking (i.e. does not return immediately) then this will explain why you are not seeing anything on the screen for a few seconds. You are currently calling this method in the main thread, so it will stop the UI from being updated until is complete.
You can make it run in the background by doing this:
- (void) getDataInBackgroundThread
{
NSAutoReleasePool *pool = [[NSAutoReleasePool alloc] init];
[self getData];
// force the table to redraw - UI operations must be on the main thread
[tableView performSelectorOnMainThread:#selector( reloadData )];
[pool drain];
}
In your main code, now instead of calling [self getData] call [self getDataInBackgroundThread];
2. getData is not blocking (asynchronous)
Even if getData is blocking, if it runs in the main thread it will still cause the UI to hang. Also, if it uses a lot of processor time it will slow down the UI and give the appearance of not running in the background.
To address this issue, you would need make sure the lengthy operation of getData really is not running in the main thread and also put in sleep() calls every so often to give some time for the UI to update.

You still haven't given enough info for people to really help, we're just guessing.
It is highly likely the delay is caused by getData. Try commenting that out or bracket it with NSLog statements to verify.
You should show us more code, specifically what is happening in getData and any delegate or notification handling implementations related to loading data.
You don't need to explicitly call [tableView reloadData] in viewDidLoad. The tableView automatically loads data the first time it is displayed.
As #dmatt said, if you are loading data asynchronously then getData would return immediately with no delay. You would typically would either respond to delegate messages or notifications (depending on how you are loading data) to reload the table when the data is finished loading and serializing.
There are lots of folks on SO who are happy to try and help you if given enough info. Especially when you offer a bounty.

Related

ABPeoplePickerNavigationController crashes in IOS 7

I have problem with ABPeoplePickerNavigationController in IOS 7 with the following error
*** -[ABPeoplePickerNavigationController respondsToSelector:]: message sent to deallocated instance 0x9b4b050
on IOS 6 it is working fine but in ios 7 it gives this error with zombies enabled without zombies it was like
Thread 1: EXC_BAD_ACCESS(code=2,address=0x0)
than i enable zombies
here is my code
- (void)viewDidLoad
{
[super viewDidLoad];
self.contacts = [[NSMutableArray alloc] initWithCapacity:10];
self.addressBook=ABAddressBookCreateWithOptions(NULL, NULL);
[self checkAddressBookAccess];
}
(void)requestAddressBookAccess
{
ContactsViewController * __weak weakSelf = self;
ABAddressBookRequestAccessWithCompletion(self.addressBook, ^(bool granted, CFErrorRef error)
{
if (granted)
{
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf accessGrantedForAddressBook];
});
}
});
}
-(void)accessGrantedForAddressBook
{
NSMutableArray *savedContacts=[[NSMutableArray alloc] initWithArray:[DatabaseHandler getAllContacts]];
if (savedContacts &&savedContacts.count!=0)
[self.contacts addObjectsFromArray:savedContacts];
}
- (IBAction)popUpAddExistingContact:(id)sender {
ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
picker.peoplePickerDelegate = self;
[picker setDelegate:self];
[self presentViewController:picker animated:YES completion:nil];
}
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
NSString *viewControllerDesc=[viewController description];
NSString *t_st = #"ABContactViewController";
NSRange rang =[viewControllerDesc rangeOfString:t_st options:NSCaseInsensitiveSearch];
if (rang.length == [t_st length])
{
navigationController.topViewController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(addPerson:)];
}
else if([navigationController isKindOfClass:[ABPeoplePickerNavigationController class]] && [viewController isKindOfClass:[ABPersonViewController class]])
{
ABPersonViewController *DVC=(ABPersonViewController*)viewController;
self.currentPerson=DVC.displayedPerson;
navigationController.topViewController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(addPerson:)];
}
else{
navigationController.topViewController.navigationItem.rightBarButtonItem = nil;
}
navigationController.topViewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:#selector(cancel:)];
}
-(IBAction)addPerson:(id)sender{
if (self.currentPerson!=NULL)
{
CFStringRef firstName;
int recordID;
firstName = ABRecordCopyValue(self.currentPerson, kABPersonFirstNameProperty);
recordID = ABRecordGetRecordID(self.currentPerson);
MyContact *contact=[[MyContact alloc] init];
contact.Name=(__bridge NSString *)(firstName);
contact.contactID=[NSString stringWithFormat:#"%i",recordID];
contact.phones=[[NSMutableArray alloc] init];
ABMultiValueRef phones = ABRecordCopyValue(self.currentPerson, kABPersonPhoneProperty);
for(CFIndex j = 0; j < ABMultiValueGetCount(phones); j++)
{
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(phones, j);
CFStringRef locLabel = ABMultiValueCopyLabelAtIndex(phones, j);
NSString *phoneNumber = (__bridge NSString *)phoneNumberRef;
[contact.phones addObject:phoneNumber];
CFRelease(phoneNumberRef);
CFRelease(locLabel);
}
CFRelease(firstName);
//CFRelease(lastName);
}
//[self dismissModalViewControllerAnimated:YES];
[self dismissViewControllerAnimated:YES completion:^(void ){
[self.popUpContactView removeFromSuperview];
}];
}
as soon as peoplepickercontroller is dismissed app crashed in ios 7
*** -[ABPeoplePickerNavigationController respondsToSelector:]: message sent to deallocated instance 0xb236c00
0x17d811: jmp 0x17d90c ; ___forwarding___ + 1020
Thread 1:EXC_BREAKPOINT (code=EXC_1386_BPT,sucode 0x0)
try to set peopleViewController delegates to nil before dismissing and disable second possible call of this action during some time (like if user pressed button several times). Assume you have a reference to ABPeoplePickerNavigationController instance. Something name like self.adressBook;
Then before dismissing PeoplePickerNavigationController set
self.adressBook.peoplePickerDelegate = nil
self.adressBook.delegate = nil;
and make sure that you do not call your peoplePickerNavigationController reference after dismissing or your reference to this instance is of weak, not assign type.
- (IBAction)popUpAddExistingContact:(id)sender {
ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
picker.peoplePickerDelegate = self;
[picker setDelegate:self];
[self presentViewController:picker animated:YES completion:nil];
}
I think it is because the view controller created is not retained,
Call [self addChildViewController:picker] or else maintain a "strong" reference for it

AppDelegate Navigation error

- (void)applicationDidFinishLaunching:(UIApplication *)application {
NSError *error = nil;
NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:#"username"];
NSString *str = [SFHFKeychainUtils getPasswordForUsername:username andServiceName:#"mybibleapp" error:&error];
NSLog(#"previous un");
NSLog(#"%#", str);
if(str != nil)
{
main_page *detailViewController = [[main_page alloc] initWithNibName:#"main_page" bundle:nil];
// Pass the selected object to the new view controller.
// detailViewController.localStringtextnote = localStringtextnote;
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
}
When I put this code for navigating to main_page it shows an error that property navigationController not found on object of appdelegate so i put this code insted of the above
main_page *log = [[main_page alloc] initWithNibName:#"main_page" bundle:nil];
[window addSubview:tabController.view];
[window addSubview:log.view];
[window makeKeyAndVisible];
the page is redirected to main_page but nothing is working in this way. no navigation in main_page is working, I cant redirect any page from the main_page. So what can I do to solve these errors.
You can create a "proxy" viewController without nib which is loaded in MainWindow's navigationController and then do something like the following, in the proxy's viewDidLoad
NSError *error = nil;
NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:#"username"];
NSString *str = [SFHFKeychainUtils getPasswordForUsername:username andServiceName:#"mybibleapp" error:&error];
NSLog(#"previous un");
NSLog(#"%#", str);
UIViewController *controller;
if (!error && nil != str) {
controller = [[DetailViewController alloc] init];
} else {
controller = [[LoginViewController alloc] init];
}
[[self navigationController] pushViewController:controller animated:YES];
[controller release];
Initial page loading is usually handled in the MainWindow.xib nib. You shouldn't have to manually load it.
Try creating a new project from a template and then do in and look at how the appDelegate and MainWindow.xib are setup.

NSOperation and EXC_BAD_ACCESS

I have a few apps which are largely data driven, so most screens are basically composed of:
Open the screen
Download the data via an NSOperation
Display data in a UITableView
Make a selection from the UITableView
Go to new screen, and start over from step 1
I am finding that everything works in normal usage, but if the user goes away from the app for a while and then comes back, I'm getting an EXC_BAD_ACCESS error when the next NSOperation runs. This doesn't seem to matter if the user sends the app into the background or not, and it only seems to occur if there's been at least a few mins since the previous data connection was made.
I realise this must be some form of over-releasing, but I'm pretty good with my memory management and I can't see anything wrong. My data calls generally look like this:
-(void)viewDidLoad {
[super viewDidLoad];
NSOperationQueue* tmpQueue = [[NSOperationQueue alloc] init];
self.queue = tmpQueue;
[tmpQueue release];
}
-(void)loadHistory {
GetHistoryOperation* operation = [[GetHistoryOperation alloc] init];
[operation addObserver:self forKeyPath:#"isFinished" options:0 context:NULL];
[self.queue addOperation:operation];
[operation release];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqual:#"isFinished"] && [object isKindOfClass:[GetHistoryOperation class]]) {
GetHistoryOperation* operation = (GetHistoryOperation*)object;
if(operation.success) {
[self performSelectorOnMainThread:#selector(loadHistorySuceeded:) withObject:operation waitUntilDone:YES];
} else {
[self performSelectorOnMainThread:#selector(loadHistoryFailed:) withObject:operation waitUntilDone:YES];
}
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
-(void)loadHistorySuceeded:(GetHistoryOperation*)operation {
if([operation.historyItems count] > 0) {
//display data here
} else {
//display no data alert
}
}
-(void)loadHistoryFailed:(GetHistoryOperation*)operation {
//show failure alert
}
And my operations generally looks something like this:
-(void)main {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSError* error = nil;
NSString* postData = [self postData];
NSDictionary *dictionary = [RequestHelper performPostRequest:kGetUserWalkHistoryUrl:postData:&error];
if(dictionary) {
NSNumber* isValid = [dictionary objectForKey:#"IsValid"];
if([isValid boolValue]) {
NSMutableArray* tmpDays = [[NSMutableArray alloc] init];
NSMutableDictionary* tmpWalksDictionary = [[NSMutableDictionary alloc] init];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyyMMdd"];
NSArray* walksArray = [dictionary objectForKey:#"WalkHistories"];
for(NSDictionary* walkDictionary in walksArray) {
Walk* walk = [[Walk alloc] init];
walk.name = [walkDictionary objectForKey:#"WalkName"];
NSNumber* seconds = [walkDictionary objectForKey:#"TimeTaken"];
walk.seconds = [seconds longLongValue];
NSString* dateStart = [walkDictionary objectForKey:#"DateStart"];
NSString* dateEnd = [walkDictionary objectForKey:#"DateEnd"];
walk.startDate = [JSONHelper convertJSONDate:dateStart];
walk.endDate = [JSONHelper convertJSONDate:dateEnd];
NSString* dayKey = [dateFormatter stringFromDate:walk.startDate];
NSMutableArray* dayWalks = [tmpWalksDictionary objectForKey:dayKey];
if(!dayWalks) {
[tmpDays addObject:dayKey];
NSMutableArray* dayArray = [[NSMutableArray alloc] init];
[tmpWalksDictionary setObject:dayArray forKey:dayKey];
[dayArray release];
dayWalks = [tmpWalksDictionary objectForKey:dayKey];
}
[dayWalks addObject:walk];
[walk release];
}
for(NSString* dayKey in tmpDays) {
NSMutableArray* dayArray = [tmpWalksDictionary objectForKey:dayKey];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"startDate" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray* sortedDayArray = [dayArray sortedArrayUsingDescriptors:sortDescriptors];
[sortDescriptor release];
[tmpWalksDictionary setObject:sortedDayArray forKey:dayKey];
}
NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO selector:#selector(localizedCompare:)];
self.days = [tmpDays sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
self.walks = [NSDictionary dictionaryWithDictionary:tmpWalksDictionary];
[tmpDays release];
[tmpWalksDictionary release];
[dateFormatter release];
self.success = YES;
} else {
self.success = NO;
self.errorString = [dictionary objectForKey:#"Error"];
}
if([dictionary objectForKey:#"Key"]) {
self.key = [dictionary objectForKey:#"Key"];
}
} else {
self.errorString = [error localizedDescription];
if(!self.errorString) {
self.errorString = #"Unknown Error";
}
self.success = NO;
}
[pool release];
}
-(NSString*)postData {
NSMutableString* postData = [[[NSMutableString alloc] init] autorelease];
[postData appendFormat:#"%#=%#", #"LoginKey", self.key];
return [NSString stringWithString:postData];
}
----
#implementation RequestHelper
+(NSDictionary*)performPostRequest:(NSString*)urlString:(NSString*)postData:(NSError**)error {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/%#", kHostName, urlString]];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[urlRequest setHTTPMethod:#"POST"];
if(postData && ![postData isEqualToString:#""]) {
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
[urlRequest setHTTPBody:[postData dataUsingEncoding:NSASCIIStringEncoding]];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
}
NSURLResponse *response = nil;
error = nil;
NSData *jsonData = [NSURLConnection sendSynchronousRequest:(NSURLRequest *)urlRequest returningResponse:(NSURLResponse **)&response error:(NSError **)&error];
NSString *jsonString = [[NSString alloc] initWithBytes: [jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
NSLog(#"JSON: %#",jsonString);
//parse JSON
NSDictionary *dictionary = nil;
if([jsonData length] > 0) {
dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:error];
}
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
return dictionary;
}
If I have the autorelease pool in place, the crash occurs on [pool release]. If I don't, then the crash just looks to appear in the main.m method, and I don't seem to get any useful information. It's difficult to track down when I have to wait 10 mins in between every test!
If anyone can offer any clues or directions to go, that'd be much appreciated.
It's almost certain you're overreleasing something in your code, seeing that the crash is occurring during a [pool release] (There's a autorelease pool in the main method as well).
You can find it using Xcode - use build and analyze to have the static analyser pinpoint potential problems. Run it and post the results.
try this:
http://cocoadev.com/index.pl?NSZombieEnabled
also, you should avoid:
1) calling UIKit methods from secondary threads
2) making (synchronous) url requests from the main thread.
you must be doing one in any case in RequestHelper's performPostRequest method.
My guess is this section
GetHistoryOperation* operation = (GetHistoryOperation*)object;
if(operation.success) {
[self performSelectorOnMainThread:#selector(loadHistorySuceeded:) withObject:operation waitUntilDone:YES];
} else {
[self performSelectorOnMainThread:#selector(loadHistoryFailed:) withObject:operation waitUntilDone:YES];
}
If the sleep happens at a bad point here, you have an object being passed to another thread. I'd find a way around having to pass the operation as the object.
This is a really old question, so sorry for the dredge, but there is no accepted answer.
I was also getting a EXC_BAD_ACCESS on NSOperationQueue -addOperation for seemingly no reason, and after a few days of hunting down memory leaks, and turning on all the debugger options i could find (malloc guard, zombies) and getting nothing, I found an NSLog warning that said: "[NSoperation subclass] set to IsFinished before being started by the queue."
When I modified my base operation subclass, so that its -cancel function only set (IsRunning = NO) and (IsFinished = YES) IF AND ONLY IF (IsRunning == YES), NSOperationQueue stopped crashing.
So if you're ever calling NSOperationQueue -cancelAllOperations, or you're doing that manually (i.e. for (NSOperation *op in queue.allOperations) ) double check to make sure that you don't set IsFinished on those operations in your subclass implementation.

How to show/hide UIImageView when I want

I'm having a little problem with an iPhone app I'm currently developing.
When the user touch a button, it calls an IBAction named refreshQuestion, which is supposed to show an image hover the screen to ask the user to wait a moment, then it has to call another function, and finally it has to hide the image.
The problem is that the image won't appear. As well as the network activity indicator.
Any help?
Here is the code :
- (IBAction)refreshQuestion:(id)sender{
pleaseWait.hidden = NO;
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[self loadData];
pleaseWait.hidden = YES;
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
EDIT :
Here is my LoadData function :
- (void)loadData{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString * idUtilisateur = [userDefaults objectForKey:#"idUtilisateur"];
NSString * stringUrlQuestion = [NSString stringWithFormat:#"http://www.mywebsiteURL"];
NSURL * urlQuestion = [NSURL URLWithString:stringUrlQuestion];
QuestionParser * parser = [[QuestionParser alloc] init];
[parser parseXMLAtURL:urlQuestion parseError:nil] ;
int nbQuestions = [parser.arrayOfQuestion count];
[parser release];
NSFetchRequest *requete = [[NSFetchRequest alloc] init];
NSEntityDescription *entite = [NSEntityDescription entityForName:#"Question" inManagedObjectContext:self.managedObjectContext];
[requete setEntity:entite];
NSSortDescriptor * sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"idQuestion" ascending:YES];
NSArray * sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[requete setSortDescriptors:sortDescriptors];
[sortDescriptor release];
[sortDescriptors release];
NSError * error;
NSMutableArray *mutableFetchResult = [[self.managedObjectContext executeFetchRequest:requete error:&error] mutableCopy];
[requete release];
if(mutableFetchResult == nil){
NSLog(#"Erreur viewWillAppear : %#", error);
}
questionDuJour = [mutableFetchResult objectAtIndex:0];
if (nbQuestions == 0){
UIAlertView* alertViewConnection = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Error while retreiving data" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertViewConnection show];
[alertViewConnection release];
}
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:#"EEEE d MMMM"];
NSLocale * localisation = [[[NSLocale alloc] initWithLocaleIdentifier:#"fr_FR"] autorelease];
[outputFormatter setLocale:localisation];
labelJour.text = [NSString stringWithFormat:#"%#",[outputFormatter stringFromDate:questionDuJour.dateQuestion]];
textQuestion.text = questionDuJour.textQuestion;
citation.text = [NSString stringWithFormat:#"%#",questionDuJour.citation];
labelAuteur.text = [NSString stringWithFormat:#"%#",questionDuJour.auteur];
[outputFormatter release];
NSLog(#"stop animating");
}
I think your code [self loadData] executes in microseconds.
Check by using this code alone,
pleaseWait.hidden = NO;
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
EDIT:
Check this, if you still get the same problem check whether you have assigned IBoutlet or not. Because what you are doing is the correct way.
Sounds like everything is executing on the UI Thread. Post your loadData method so we can see what its doing. Chances are you have to convert this method to use one of the asynchronous techniques which will return immediately and allow the UI thread to continue. You can then detect when its done loading the data and change the visibility of the image again.

ipad subview not loading before code is executing

I have a command that should be loading a subview before a particular piece of time intensive code executes. However the command runs, the timely code executes and then the subview shows up. Is there anything I can do to fix this problem?
progressViewController = [[ProgressView alloc] initWithNibName:#"ProgressView" bundle:[NSBundle mainBundle]];
[self.view addSubview:[progressViewController view]];
NSString *name=#"guy";
NSString *encodedName =[[NSString alloc] init];
int asci;
for(int i=0; i < [name length]; i++)
{
//NSLog(#"1");
asci = [name characterAtIndex:i];
NSString *str = [NSString stringWithFormat:#"%d,", asci];
encodedName =[encodedName stringByAppendingFormat: str];
}
NSString *urlString = [NSString stringWithFormat:#"someurl.com"];
NSURL *theUrl = [[NSURL alloc] initWithString:urlString];
NSString *result=[NSString stringWithContentsOfURL:theUrl];
result = [result substringFromIndex:61];
result = [result substringToIndex:[result length] - 20];
NSLog(result);
outLab.text=result;
[[progressViewController view] removeFromSuperview];
1) try
[self.view setNeedsUpdating]
after adding the subview
2)
try splitting the time intensive into another thread....
- (void) f
{
// executed in main UI thread
progressViewController = [[ProgressView alloc] initWithNibName:#"ProgressView" bundle:[NSBundle mainBundle]];
[self.view addSubview:[progressViewController view]];
[NSThread detachNewThreadSelector:#selector(doCompute) toTarget:self
withObject:nil];
}
- (void) doCompute
{
// in a different thread....so we need a autoreleasepool
NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
// do your computation here...
[self performSelectorOnMainThread:#selector(taskComplete:)
withObject:result waitUntilDone:NO];
[autoreleasepool release];
}
- (void) taskComplete
{
// executed in UI thread
[self.progressView removeFromSuperView];
}
You could subclass the view and then use the viewDidLoad function to execute your long running code.