A issue of a variable regarding to refreshing table view - ios

I have a tableview using ODRefreshControll. And i have a uislider which is in another view controller (let say myViewController) and this slider is changing a variable (let say myVariable) of tableview. The main issue is if i change myVariable from myViewController with slider and refresh the tableview, myVariable turns its initial value. I will provide my code but it is a little bit mess code, so please ask anything you do not understand from code.
Here is my code:
At myTableView.h:
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#import "ODRefreshControl.h"
#interface myTableView : UITableViewController
-(void)gettingVariableFromMyViewController;
#end
At myTableView.m
#import "MekanListesi.h"
#import "AppDelegate.h"
#import "Ayarlar.h"
#interface myTableView ()
#property(strong)NSNumber *myVariable;
#end
#implementation myTableView
#synthesize myVariable;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
-(void)gettingVariableFromMyViewController{
NSString *unsettedVariable = [(AppDelegate *)[[UIApplication sharedApplication] delegate] variableUniversal];
if (!unsettedVariable) {
unsettedVariable= #"10000000000000000";
}
NSNumberFormatter * NSNF= [[NSNumberFormatter alloc] init];
[NSNF setNumberStyle:NSNumberFormatterDecimalStyle];
self.myVariable=[DegmesinEllerimiz numberFromString:AlinanYariCap];
}
- (void)dropViewDidBeginRefreshing:(ODRefreshControl *)refreshControl
{
double delayInSeconds = 1;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[refreshControl endRefreshing];
});
}
At myViewController.h
#import <UIKit/UIKit.h>
#interface myViewController : UIViewController
#property (weak, nonatomic) IBOutlet UISlider *mySlider;
- (IBAction)actionMySlider:(id)sender;
#property (weak, nonatomic) IBOutlet UILabel *myVariabelLabel;
#end
At myViewController.m
#import "myViewController.h"
#import "AppDelegate.h"
#import "myTableView.h"
#interface myViewController()
#end
#implementation myViewController
#synthesize myVariableLabel;
#synthesize mySlider;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)actionMySlider:(id)sender{
myVariableLabel.text = [NSString stringWithFormat:#"%1.1f",mySlider.value];
[(AppDelegate *)[[UIApplication sharedApplication] delegate] setuniversalVariable:[NSString stringWithFormat:#"%f",mySlider.value]];
myTableView *MTV=[[myTableView alloc]init];
[MTV gettingVariableFromMyViewController];
[MTV.tableView reloadData];
}
(At appdelegate universalVariable setted as
#property(nonatomic,retain)NSString *universalVariable;
#synthesize universalVariable;
)
note: I am coping and pasting that code from xcode and make some changes with names of methods, classes and variables due to the fact that my native language is not English, so there can be some mistakes about names of those, Please warn me if you see one of those errors.
Thank you.

The problem is not the pull to refresh, the problem is in your code that somewhere you are setting the wrong value for your variable. Also where are you setting the new value for your variable, because in gettingVariableFromMyViewController you are checking the value store in your app delegate so if you don't set anywhere the new value in the app delegate, the gettingVariableFromMyViewController will return/set the same value #"10000000000000000

Related

Delegate in Objective-C

I am new at Objective-C, and I'm trying to understand delegates. I have searched and read a lot, but nothing is really helping me understand. I think that best way to understand this might be asking a question with a sample app.
I'm trying to create a grade calculator application to test my skills. Here are my files:
mainTableViewController.h
#import <UIKit/UIKit.h>
#interface mainTableViewController : UITableViewController
#end
mainTableViewController.m
#import "mainTableViewController.h"
#import "addLectureViewController.h"
#interface mainTableViewController ()
#end
#implementation anaTableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
[lectureName count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
return cell;
}
#end
addLectureViewController.h
#import <UIKit/UIKit.h>
#interface addLectureViewController : UIViewController
#property (weak, nonatomic) IBOutlet UITextField *lectureNameTextField;
- (IBAction)addButtonPressed:(id)sender;
#property NSMutableArray *lectureName;
#property NSObject *lecture;
#end
addLectureViewController.m
#import "addLectureViewController.h"
#interface addLectureViewController ()
#end
#implementation addLectureViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_lectureName = [[NSMutableArray alloc] init];
_lecture = [[NSObject alloc] init];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (IBAction)addButtonPressed:(id)sender {
_lecture = _lectureNameTextField.text;
[_lectureName addObject:_lecture];
NSLog(#"%#",_lectureName);
}
#end
Everything is okay so far. But when i try to use the _lectureName NSMutableArray at mainTableViewController.m, I can't see the array.
I know the codes for printing the array in tableView. I know they are not at there right now. I just don't understand implement delegate codes to my code.
If You want to display something on the rows of the table, You can take an NSArray and you have to return the count of the array in the delegate method:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return array.count;
}
Otherwise, table will not display any elements. And delegate method cellForRowAtIndexPath will only be called if you are returning a particular array count of number count in your numberOfRowsInSection method.
You can take reference from these links to understand delegates:
http://www.tutorialspoint.com/ios/ios_delegates.htm
How do I set up a simple delegate to communicate between two view controllers?
http://code.tutsplus.com/tutorials/ios-sdk-custom-delegates--mobile-10848
But in the case of tableView, the delegate methods are internally defined and triggered internally. We just need to set those delegates to the controller which acts as a listener.
The below code might have syntax errors but they can provide a summary of delegates for this code.
Make the following changes :-
mainTableViewController.h
#import <UIKit/UIKit.h>
#interface mainTableViewController : UITableViewController
#property(strong, nonatomic) NSMutableArray *lectureName
#end
Synthesize the property lectureName in mainTableViewController.m
Then make the following changes in addLectureViewController.h
#import <UIKit/UIKit.h>
#import "mainTableViewController.h"
#interface addLectureViewController : UIViewController
#property (weak, nonatomic) IBOutlet UITextField *lectureNameTextField;
- (IBAction)addButtonPressed:(id)sender;
#property(weak, nonatomic) id<mainTableViewController> delegate;
#property NSMutableArray *lectureName;
#property NSObject *lecture;
#end
Synthesize the property delegate in addLectureViewController.m
Then make the following change :-
- (IBAction)addButtonPressed:(id)sender {
_lecture = _lectureNameTextField.text;
[_lectureName addObject:_lecture];
NSLog(#"%#",_lectureName);
delegate.lectureName=_lectureName;
}
Assuming that you are pushing addLectureViewController from mainTableViewController, also include the following code in prepareForSegue of mainTableViewController (or whatever method in which you are pushing addLectureViewController). :-
addLectureViewController *vc=[[addLectureViewController alloc] init];
vc.delegate=self;
// Push vc
The above code actually creates a weak property of type id<mainTableViewController> called delegate (weak in order to prevent reference cycles). This way, addLectureViewController can update mainTableViewController's property.
Points:
Why is the class in mainTableViewController.m named anaTableViewController. It should be mainTableViewController (almost always, until you get more advanced).
mainTableViewController and addLectureViewController should start with capital letters.
The only way for mainTableViewController to access lecture is through a addLectureViewController object, e.g.
addLectureViewController *alvc = // *something* here
NSArray *localLecture = [alvc lecture];
Figure out how you have access to an addLectureViewController and you will have solved your problem.

Change UILabel text from subview using delegate

I have a view with a label in it. The lower side of this view is filled with a subview which has it’s own view controller. This subview has a button. My goal: I want to change the label by pressing the button in the subview.
I have tried the code beneath. It works fine when I let the ViewWillAppear method of the delegate call the ‘doSomeTask’ method of the SubviewController. A timer begins to count and after a few seconds, the SubviewController calls the delegates changeLabel method, and the label is changed. However, when I call the ‘doSomeTask’ method manually by pressing the button, the delegate isn’t listening. The call doesn’t reach the changeLabel method.
Probably I am doing something ridiculously stupid here. Forgive me, I’m just learning iOS programming. Thanks in advance for all the feedback.
MyViewController.h
#import <UIKit/UIKit.h>
#import "MySubViewController.h"
#interface MyViewController : UIViewController
#property (strong, nonatomic) IBOutlet UIView *detailView;
#property (strong, nonatomic) IBOutlet UILabel *theLabel;
- (IBAction)changeLabel:(id)sender;
#end
MyViewController.m
#import "MyViewController.h"
#import "MySubViewcontroller.h"
#interface MyViewController ()
#end
#implementation MyViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
MySubViewController *subVC = [[MySubViewController alloc] init];
[self addChildViewController:subVC];
[self.detailView addSubview:subVC.view];
// [subVC setDelegate:self]; (no success trying this)
[subVC didMoveToParentViewController:self];
}
-(void)viewWillAppear:(BOOL)animated
{
MySubViewController *mySubVC = [[MySubViewController alloc] init];
[mySubVC setDelegate:self];
[mySubVC doSomeTask]; // this works fine
}
// delegate method
- (void)changeLabel{
self.theLabel.text = #"Hello!";
}
MySubviewController.h
#import <UIKit/UIKit.h>
#protocol MySubViewControllerDelegate <NSObject>
#required
- (void)changeLabel;
#end
#interface MySubViewController : UIViewController
#property (nonatomic, assign) id delegate;
- (IBAction)changeButton:(id)sender;
- (void)doSomeTask;
- (void)goChangeLabel;
#end
MySubViewController.m
#import "MySubViewController.h"
#interface MySubViewController ()
#end
#implementation MySubViewController
#synthesize delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)goChangeLabel
{
[[self delegate] changeLabel];
}
- (void)doSomeTask
{
[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:#selector(goChangeLabel) userInfo:nil repeats:NO];
}
- (IBAction)changeButton:(id)sender {
// [self doSomeTask]; (no succes trying this)
}
#end
Your problem is this:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
MySubViewController *subVC = [[MySubViewController alloc] init];
[self addChildViewController:subVC];
[self.detailView addSubview:subVC.view];
// [subVC setDelegate:self]; (no success trying this)
[subVC didMoveToParentViewController:self];
}
-(void)viewWillAppear:(BOOL)animated
{
MySubViewController *mySubVC = [[MySubViewController alloc] init];
[mySubVC setDelegate:self];
[mySubVC doSomeTask]; // this works fine
}
In these 2 methods you have created 2 separate variables of type MySubViewController. You have only set the delegate on the variable created inside viewWillAppear.
These are not static classes, singletons or anything else similar. If you create a variable of one type it is in no way linked to the other. The same way you can create multiple NSString's that have no bearing on each other.
Create it like so:
#implementation MyViewController
{
MySubViewController *_subVC;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_subVC = [[MySubViewController alloc] init];
}
now you can use _subVC everywhere in that file as the one reference

UITextFieldDelegate not working

I'm trying to separate the UITextViewDelegate methods from the main class of my project, I created a class to manage the delegate methods, but I can not change the values of the IBOulets from the main class.
I made a test project with a ViewController and a TextFieldController, in the Storyboard I add a text field and a label. What I want to do is change the text of the label when I start to write in the text field. Here is the code:
ViewController.h:
#import <UIKit/UIKit.h>
#import "TextFieldController.h"
#interface ViewController : UIViewController
#property (strong, nonatomic) IBOutlet UITextField *textField;
#property (strong, nonatomic) IBOutlet UILabel *charactersLabel;
#end
ViewController.m:
#import "ViewController.h"
#interface ViewController ()
#property (nonatomic, strong) TextFieldController *textFieldController;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_textFieldController = [[TextFieldController alloc] init];
_textField.delegate = _textFieldController;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#end
TextFieldController.h:
#import <UIKit/UIKit.h>
#import "ViewController.h"
#interface TextFieldController : UIViewController <UITextFieldDelegate>
#end
Text Field Controller.m:
#import "TextFieldController.h"
#interface TextFieldController ()
#property ViewController *viewController;
#end
#implementation TextFieldController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (BOOL) textFieldShouldBeginEditing:(UITextField *)textField {
NSLog(#"hello");
_viewController.charactersLabel.text = #"hello";
return YES;
}
#end
When I start writing in the text field the message "Hello" is printed in the log, but the text of the label does not change. I want to know how to change the label text value from the other class.
First change the TextFieldController.h like this:
#import <UIKit/UIKit.h>
#import "ViewController.h"
#interface TextFieldController : NSObject <UITextFieldDelegate>
{
}
#property (nonatomic, assign) ViewController *viewController;
#end
Then change your TextFieldController.m file like this:
#import "TextFieldController.h"
#interface TextFieldController ()
#end
#implementation TextFieldController
- (BOOL) textFieldShouldBeginEditing:(UITextField *)textField {
NSLog(#"hello");
self.viewController.charactersLabel.text = #"hello";
return YES;
}
#end
In the ViewController.m do like that:
#import "ViewController.h"
#interface ViewController ()
#property (nonatomic, strong) TextFieldController *textFieldController;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_textFieldController = [[TextFieldController alloc] init];
_textFieldController.viewController = self;
_textField.delegate = _textFieldController;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#end
This will work but I personally dont like that way you took.
Good luck :)
It's failing because _viewController is nil. You need to assign the viewController property in your delegate in order to support the two way communication.
Also, I'd strongly recommend you make your delegate object a subclass of NSObject, and not UIViewController. It does nothing with controlling views. You can just manually instantiate it in your ViewController objects viewDidLoad.
In TextViewController I don't see where the viewController property (_viewController ivar) is being set so it is probably nil. You should set it when you create the TextViewController instance.
When you are navigating to other controllers using storyboad's segue then you need to implement prepareForSegue method to initialised its properties as follows
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"segue for textFieldController"])
{
TextFieldController *_textFieldController = [segue destinationViewController];
_textField.delegate = _textFieldController;
}
}
But I was wondering, why are you setting textFieldDelegate here, why can't you set in TextFieldController's viewDidLoad method as then you didn't you to implement above prepareForSegue method call?
Besides you are keeping strong reference of each other and you are creating strong retain cycle.
One more thing, following code
_textField.delegate = _textFieldController;
will not work, until textFieldController is loaded and its viewDidLoad method is being called as you are only initialising it but its outlets will not be connected until view is loaded into navigation stack.

How to implement a progress bar on top of UIWebView?

I am developing application for iOS7 in xcode 5. I have a view controller ADMSViewController
The .h file is as follows
#import <UIKit/UIKit.h>
#import "IMTWebView.h"
#interface ADMSViewController : UIViewController <UIWebViewDelegate,IMTWebViewProgressDelegate>
{
NSString *barcode;
NSString *vinNumber;
NSTimer *timer;
}
#property (nonatomic,retain) IBOutlet UIWebView *webView;
#property (nonatomic,retain) IBOutlet UIProgressView *progressView;
#end
The .m file is as follows
#import "ADMSViewController.h"
#import <QuartzCore/QuartzCore.h>
#implementation ADMSViewController
#synthesize webView;
#synthesize progressView;
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://google.com/"]]];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.navigationController setNavigationBarHidden:YES animated:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)webView:(IMTWebView *)_webView didReceiveResourceNumber:(int)resourceNumber totalResources:(int)totalResources {
[self.progressView setProgress:((float)resourceNumber) / ((float)totalResources)];
if (resourceNumber == totalResources) {
_webView.resourceCount = 0;
_webView.resourceCompletedCount = 0;
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
self.webView = nil;
self.progressView = nil;
}
#end
The IMTWebview.h file is as follows
#import <UIKit/UIKit.h>
#class IMTWebView;
#protocol IMTWebViewProgressDelegate <NSObject>
#required
- (void) webView:(IMTWebView*)webView didReceiveResourceNumber:(int)resourceNumber totalResources:(int)totalResources;
#end
#interface IMTWebView : UIWebView {
}
#property (nonatomic, assign) int resourceCount;
#property (nonatomic, assign) int resourceCompletedCount;
#property (nonatomic, assign) id<IMTWebViewProgressDelegate> progressDelegate;
#end
the IMTWebCiew.m file is as follows
#import "IMTWebView.h"
#interface UIWebView ()
-(id)webView:(id)view identifierForInitialRequest:(id)initialRequest fromDataSource:(id)dataSource;
-(void)webView:(id)view resource:(id)resource didFinishLoadingFromDataSource:(id)dataSource;
-(void)webView:(id)view resource:(id)resource didFailLoadingWithError:(id)error fromDataSource:(id)dataSource;
#end
#implementation IMTWebView
#synthesize progressDelegate;
#synthesize resourceCount;
#synthesize resourceCompletedCount;
-(id)webView:(id)view identifierForInitialRequest:(id)initialRequest fromDataSource:(id)dataSource
{
[super webView:view identifierForInitialRequest:initialRequest fromDataSource:dataSource];
return [NSNumber numberWithInt:resourceCount++];
}
- (void)webView:(id)view resource:(id)resource didFailLoadingWithError:(id)error fromDataSource:(id)dataSource {
[super webView:view resource:resource didFailLoadingWithError:error fromDataSource:dataSource];
resourceCompletedCount++;
if ([self.progressDelegate respondsToSelector:#selector(webView:didReceiveResourceNumber:totalResources:)]) {
[self.progressDelegate webView:self didReceiveResourceNumber:resourceCompletedCount totalResources:resourceCount];
}
}
-(void)webView:(id)view resource:(id)resource didFinishLoadingFromDataSource:(id)dataSource
{
[super webView:view resource:resource didFinishLoadingFromDataSource:dataSource];
resourceCompletedCount++;
if ([self.progressDelegate respondsToSelector:#selector(webView:didReceiveResourceNumber:totalResources:)]) {
[self.progressDelegate webView:self didReceiveResourceNumber:resourceCompletedCount totalResources:resourceCount];
}
}
#end
My issue is that the progress bar is not animating in the webview. Please help me as I am a newbie to ios development. If there is any other method to implement the same, do inform me.
Thank you in advance for your answers.
For this kind of thing, you can only really 'detect' page size by using Content-Length headers, but otherwise you can still present a loading control (like one of the moving zebra crossing type bars which doesn't show a discrete % progress but shows that activity is occurring.. or even just a UIActivityIndicator). You could try a ready-made class like http://allseeing-i.com/ASIHTTPRequest/ASIWebPageRequest too, which CAN show progress. The author states:
ASIWebPageRequests do not currently support progress tracking for an entire request with its external resources. However, progress updates from external resource requests are passed on to your delegate, so with a bit of work it may be possible to implement this yourself.

view did load but not viewDidLoad

I have two view controllers: BSViewController and BSotherViewController. BSViewController has a button on it that is segues to BSotherViewController. That part works fine and I can see the one VC and then the "other" VC when I run on the simulator. But I have an NSLog(#"other"); in BSotherViewController's -viewDidLoad which is not showing in the console. A similar NSLog(#"other"); in BSViewController's -viewDidLoad which is showing in the console. I suspect the problem is the lack of an IBAction but I cannot figure where it should go and how it should be linked in the storyboard.
BSViewController.h
#import <UIKit/UIKit.h>
#interface BSViewController : UIViewController
#property (nonatomic) NSInteger number;
#end
BSViewController.m
#import "BSViewController.h"
#interface BSViewController ()
#end
#implementation BSViewController
#synthesize number;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.number = 25;
NSLog(#"number: %d", self.number);
}
#end
BSotherViewController.h
#import <UIKit/UIKit.h>
#interface BSotherViewController : UIViewController
#property (nonatomic) NSInteger anumber;
#end
BSotherViewController.m
#import "BSotherViewController.h"
#include "BSViewController.h"
#interface BSotherViewController ()
#end
#implementation BSotherViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
NSLog(#"other number:");
[super viewDidLoad];
// Do any additional setup after loading the view.
BSViewController *view = [[BSViewController alloc] init];
self.anumber = view.number;
NSLog(#"other number: %d", self.anumber);
}
In the storyboard is the second view controller set up as a BSotherViewController? You can verify by hovering over the view controller icon in the storyboard.
If it's not, then click it and go to the identity controller and type it in.

Resources