Communication between UITableViewDataSource and UIViewController - ios

I have a tableview inside a viewcontroller and datasource of tableview is separate class, which is the best way to notify viewcontroller that some data has been added/deleted so it can add/remove rows to data ?
One idea I have is to use delegates but It will be like
Callback from webservice to Datasource -->
Fire delegate method from datasource to viewcontroller
This is giving me feeling that I am doing something wrong, Help !!

You can create weak property in your other class (the one with datasource) to hold reference to the view controller:
#property (nonatomic, weak) MyViewController *viewController;
and when you add/delete row just call appropriate method on your view controller, something like that:
//Row deleted
[self.viewController deleteRowAtIndexPath:indexPath];
Of course you have to add this method to your view controller.
The last step you have to do is connect view controller with your other class.
In view controller in the same place where you set up table view delegate do something like that:
tableView.delegate = otherClass; //<- this is the class you store table view delegate.
otherClass.viewController = self;
Note that this is just one way you can do this, the other one can be delegate (as you mentioned above) or blocks, notifications, etc.
// Extended
With block you have to do it like that.
In other class .h:
// create typedef to avoid typing all block definition
typedef void (^CompleteBlock) (NSIndexPath *indexPath);
//Declare property
#property (nonatomic, copy) CompleteBlock removeRowCompleteBlock;
// in .m file call block where you remove row:
if (self. removeRowCompleteBlock)
self. removeRowCompleteBlock(indexPath);
In view controller file after you create instance of other class add remove row block:
tableView.delegate = otherClass; //<- this is the class you store table view delegate.
otherClass.removeRowCompleteBlock = ^(NSIndexPath *indexPath) {
// od something
NSLog(#"Row removed: %#", indexPath);
};

Related

Where to set delegate = self? Or should I just use a different design pattern?

EDIT: edited for clarity
Disclaimer: I'm new and pretty bad. But I have tried very hard and read lots of stuff to figure this out, but I have not...
I think my whole delegate pattern would work, except I can't figure out how to set the delegate property of ViewController to self in the MatchLetter class. The reason is because I can't figure out how to call code there. It's not a view controller, so viewDidLoad or prepareForSegue won't work.
This is what I've got:
ViewController.h
#import <UIKit/UIKit.h>
#class ViewController;
#protocol letterMatchProtocol <NSObject>
- (BOOL) isLetterMatch:(char) firstLetter;
#end
#interface ViewController : UIViewController
#property (nonatomic, weak) id <letterMatchProtocol> delegate;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
char c = 'a';
// This is the method I want to delegate to MatchLetter, to have a BOOL returned
BOOL returnValue = [self.delegate isLetterMatch:c];
}
#end
MatchLetter.h
#import <Foundation/Foundation.h>
#import "ViewController.h"
#interface Delegate : NSObject <letterMatchProtocol>
#end
MatchLetter.m
#import "MatchLetter.h"
#implementation Delegate
// this is the code I think I need to run here, to set the delegate property...
// ViewController *viewController = [ViewController new];
// viewController.delegate = self;
// ... so that isLetterMatch can be run here from ViewController.m
// But I don't know where to put this code, or how to get it to run before the ViewController
// especially since there are no segues or views to load.
- (BOOL) isLetterMatch:(char)firstLetter {
if (firstLetter == 'a') {
return YES;
}
else {
return NO;
}
}
#end
Can somebody please tell me the best way to proceed? Thanks for reading
You asked "Where to set delegate = self? Or should I just use a different design pattern?".
Answer: Don't. An object should never be it's own delegate.
Your code is quite a mess.
Don't name a class "Delegate". A delegate is a design pattern. The whole point of a delegate is that any object that conforms to a particular protocol ("speaks the language") can serve as the delegate. You don't need to know what class of object is serving as the delegate, but only that it speaks the language you need.
An analogy: When you call the operator, you don't care who is working the operator desk. You don't care about his/her gender, religion, ethnic background, how tall they are, etc. You just care that they speak your language.
Likewise, when you set up a delegate, it doesn't matter what type of object gets set as the delegate. All that matters is that the object that is the delegate conforms to the protocol for that delegate.
A table view can have ANY object serve as it's delegate, as long as that object conforms to the UITableViewDelegate protocol. You usually make you view controller be the table view's delegate, but you don't have to. You could create a custom class that manages your table views, and have it be the delegate. There is no "TableViewDelegate" object class. There is instead a UITableViewDelegate protocol, and any object that conforms to the protocol can act as a table view's delegate.
Edit: Your question is confusing. I think what you're proposing is that your Delegate class would create a view controller and make itself the delegate for the view controller.
If that's what you are talking about, your thinking is backwards. The view controller is using the Delegate class as a helper class. Any given instance of a view controller class can create an instance of the Delegate class and set it as it's delegate if it desires. You might have 3 instances of ViewController at one time, each with it's own instance of your Delegate class.
Thus, the ViewController object is the one that should create and set up an instance of Delegate if it needs one:
- (void) viewDidLoad;
{
self.delegate = [[Delegate alloc] init];
//other setup here
}

Invoke Method in Different Class

I have a class that subclasses UITableViewController. Based on user actions that are recognized in this class, I need to call a method on a table in the UIViewController were the table is instantiated. I can't figure out how to do this.
I tried to make the function static, but that won't work since there is an instance variable that I need to reach. I could probably use NSNotificationCenter but my intuition is that there is a better way. Can someone help? Thanks!
MonthsTableViewController.h
#interface MonthsTableViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate>
{
NSArray *monthsArray;
}
#end
MonthsTableViewController.m
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
NSLog(#"calling the UIViewController");
//this is where I am stuck!!!
}
SubscribeViewController.h
#interface SubscribeViewController : UIViewController <SIMChargeCardViewControllerDelegate>
{
MonthsTableViewController *monthsController;
IBOutlet UITableView *monthsTable;
}
- (void) snapMonthsToCenter;
#end
SubscribeViewController.m
- (void) snapMonthsToCenter {
// snap the table selections to the center of the row
NSLog(#"method called!");
NSIndexPath *pathForMonthCenterCell = [monthsTable indexPathForRowAtPoint:CGPointMake(CGRectGetMidX(monthsTable.bounds), CGRectGetMidY(monthsTable.bounds))];
[monthsTable scrollToRowAtIndexPath:pathForMonthCenterCell atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}
Basically in order to do this, you need a reference to your UIViewController from your UITableViewController. This will allow you to call the methods of this object. Typically you would call this property a delegate, because you're assigning the "parent" UIViewController as the delegate of the "child" UITableViewController.
Modify your UITableViewController (MonthsTableViewController.h) to add a delegate property like so:
#interface MonthsTableViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate>
{
NSArray *monthsArray;
id delegate;
}
#property (nonatomic, retain) id delegate;
#end
You will need to #synthesize the property in your .m file. You'll also want to import SubscribeViewController.h in your header here, if you haven't already.
Then, when you instantiate your MonthsTableViewController, set the delegate to your current object MonthsTableViewController like so:
MonthsTableViewController *example = [[MonthsTableViewController alloc] init.... // This is the line you should already have
[example setDelegate:self]; // Set this object's delegate property to the current object
Now you have access to the parent SubscribeViewController from your MonthsTableViewController. So how do you call functions? Easy! You can either hardcode the method call, or, to be super safe, use respondsToSelector::
[(MonthsTableViewController*)[self delegate] snapMonthsToCenter];
In your case, the above code is absolutely fine, because you know that this method will always exist on this object. Typically, however, delegates are declared as protocols that may have optional methods. This means that although methods are declared in the #interface, they may not actually exist (be implemented) in the object. In this case, the following code would be used to make sure that the method can actually be called on the object:
if([[self delegate] respondsToSelector:#selector(snapMonthsToCenter)]) {
[[self delegate] snapMonthsToCenter];
}

Accessing a TableView within a ViewController

I've got a ViewController that has a UITableView within it. When I'm watching tutorials people are using things like this:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _Title.count;
}
How am I able to generate the stubs without firstly creating the class with them in. When I made the class I selected it as a UIViewController. I've been playing around trying to auto generate the stubs but all to no avail.
Simply add the UITableViewDataSource (and most likely the UITableViewDelegate) to your UIViewController declaration. Example:
// MyViewController.h
#interface MyViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
// ...
#end
After that your implementation file MyViewcontroller.m should help you with the code completion.
One note: don't forget to set yourself as dataSource:
_tableview.dataSource = self;
If you added the tableview by code, you need to create a property (weak) in order to have a reference to your table view after adding it to your view controller's subview. If you add it by using interface builder, you need to create a iboutlet property that will allow you to "bind" your table view property with the xib/storyboard file representing your view controller. Alternatively, you can use UITableViewController as the parent class of your view controller. This class already has a property to access the table view in your view controller.
Tell your controller that you need to conform to the table view protocols and they will start to auto-complete when you try to type them in. You can check the docs of a protocol to find the available methods. Checking the UITableView docs would tell you about the relevant data source and delegate:
The data source must adopt the UITableViewDataSource protocol and the delegate must adopt the UITableViewDelegate protocol.
In your header file:
#interface MyViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
You have a couple of options.
You could make your class inherit from UITableViewController instead of UIViewController. This will give you a tableView so you don't need to make one.
Or...
Your UIViewController could implement the protocols UITableViewDataSource and UITableViewDelegate. Then set the dataSource and delegate properties of your table view to self (your view controller containing the table).
-First of all you may need to add datasource and delegate of UITableViewController in your UIViewController header file
#interface MyViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
and then implement the required and optional methods to populate the data in your _tableView.
Sample Code for TableView demonstration by Apple:
https://developer.apple.com/library/ios/samplecode/TableViewSuite/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007318

passing data value between two view controller using custom protocol

1) I Am passing the value between two view controller using custom
protocol..But the value always showing NULL.
I need to pass the value from second view controller to first view controller
2) In Secondview controller.h
#protocol PopoverTableViewControllerDelegate <NSObject>
#property (nonatomic, strong) id<PopoverTableViewControllerDelegate>myDelegate;
3) secondview controller.m
(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary*dict=[sercharray objectAtIndex:index];
str=[dict objectForKey:#"id"];
NSLog(#"test value %#",str);
[self.myDelegate didSelectRow:str];
NSLog(#"delegate value %#",self.myDelegate);
//THIS VALUE ALWAYS SHOWING NULL AND ALSO I SHOULD PASS THIS VALUE TO FIRST VIEW
CONTROLLER.I SHOULD USE DISMISS VIEW CONTROLLER.
[self dismissViewControllerAnimated:YES completion:nil];
}
4) First View controller.h
#interface Firstviewcontroller :
UIViewController<PopoverTableViewControllerDelegate>
5) First view controller.m
secondviewcontroller *next=[[seconviewcontroller alloc]init];
next.myDelegate=self;
(void)didSelectRow:(NSString *)cellDataString {
passstring = cellDataString;
NSLog(#"pass string %#",pass string);
//first view controller str variable value i need to pass this string[passstring].
}
I think you might be a little confused about what Delegation is used for and why. For example you might want to make a protocol in a UIViewController subclass if you were doing some kind of action in that ViewController and needed to inform another subclass that that action is being taken, or of the result of that action. Now in order for the subclass that wants to know about the action(the receiver), it has to conform to that protocol in it's header file. You also must "set" the delegate to the receiving class/controller. There are many ways to get a reference to the receiving controller/class to set it as the delegate but a common mistake is allocating and initializing a new instance of that class to set it as the delegate, when that class has already been created.What that does is set your newly created class as the delegate instead of the class that's already been created and waiting for a message. What your trying to do is just pass a value to a Newly created class. Since your just creating this UIViewController class all thats needed for that is a Property in the receiver(ViewControllerTwo). In your case a NSString:
#Property (nonatiomic, retain) NSString *string; //goes in ViewControllerTwo.h
and of course don't forget in the main:
#synthesize string; //Goes in ViewControllerTwo.m
Now there is no need for a setter in your ViewControllerTwo.
- (void)setString:(NSString *)str //This Method can be erased
{ //The setter is created for free
self.myString = str; // when you synthesized the property
}
The setter and Getters are free when you use the #synthesize. Just Pass the value over to the ViewController. The implementation is identical to your code except for the delegate:
ViewControllerTwo *two = [[ViewControllerTwo alloc] initWithNibName:#"ViewControllerTwo" bundle:nil];
[two setString:theString];
[self.navigationController pushViewController:two animated:YES];
[two release];

is it possible to segue from a UITableViewCell on a UIView to another view

Xcode 4.6.1 iOS 6 using storyboards
My problem is this
I have a UITableView with dynamic prototype cells on a UIView in a UIViewController (that is itself embedded in a navigation controller) and I want to segue from one specific cell to another view
(Before anyone suggests I should just be using a UITableViewController , I do have other things on the UIView, so i'm set up this way for a reason.)
Now i'm not sure how to go about creating the segue
If I drag from the prototype UITableViewCell to create a segue , all the generated cells automatically call the the segue - when i need only one to do so. This is normal behaviour and I would get around this if i was using a UITableViewController by creating the segue by dragging from UITableViewController and calling [self performSegueWithIdentifier:.... From my didSelectRowAtIndexPathMethod so only the specific cell I want to perform this segue triggers it.
I don't have a UITableViewController in this case - just my UITableView on a UIView that is part of a UIViewController subclass
I've been playing around and I have just discovered that i cannot drag from the UITableView - doesn't let you do that, so that was a deadend.
My only choice that seemed left to me was to drag from the UIViewController
So i tried that and of course XCode throws up an error on the perform segue line telling me i have ... No visible interface for 'LocationTV' declares the selector performSegueWithIdentifier. LocationTv being my tableview subclass.
What is the correct way to attempt to call the new view in this situation
Thank
Simon
First of all segues can be use only between UIViewControllers. So in case you want to perform a segue between two views that are on the same view controller, that's impossible.
But if you want to perform a segue between two view controllers and the segue should be trigger by an action from one view (inside first view controller) well that's possible.
So in your case, if I understand the question, you want to perform a segue when the first cell of a UITableView that's inside of a custom UIView is tapped. The easiest approach would be to create a delegate on your custom UIView that will be implemented by your UIViewController that contains the custom UIView when the delegate method is called you should perform the segue, here is a short example:
YourCustomView.h
#protocol YourCustomViewDelegate <NSObject>
-(void)pleasePerformSegueRightNow;
#end
#interface YourCustomView : UIView {
UITableView *theTableView; //Maybe this is a IBOutlet
}
#property(weak, nonatomic) id<YourCustomViewDelegate>delegate;
YourCustomview.m
#implementation YourCustomview
# synthesise delegate;
//make sure that your table view delegate/data source are set properly
//other methods here maybe
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.row == 0) { //or any other row if you want
if([self.delegate respondsToSelector:#selector(pleasePerformSegueRightNow)]) {
[self.delegate pleasePerformSegueRightNow];
}
}
}
YourTableViewController.h
#interface YourTableViewController : UIViewController <YourCustomViewDelegate> {
//instance variables, outlets and other stuff here
}
YourTableViewController.m
#implementation YourTableViewController
-(void)viewDidLoad {
[super viewDidLoad];
YourCustomView *customView = alloc init....
customView.delegate = self;
}
-(void)pleasePerformSegue {
[self performSegueWithIdentifier:#"YourSegueIdentifier"];
}
You can create any methods to your delegate or you can customise the behaviour, this is just a simple example of how you can do it.
My Solution
I ended up using a delegation pattern
I made a segue dragging from the my UIViewController - specifically dragging from the viewController icon (the orange circle with a white square in it - from the name bar thats under the view in the storyboard - although you could also drag from the sidebar ) to the view that i wanted to segue to.
I needed to trigger this segue from a table view cell on a table view.
TableView Bit
So i declared a protocol in my tableview header file - which is called LocationTV.h - as follows
#protocol LocationTVSegueProtocol <NSObject>
-(void) makeItSegue:(id)sender;
#end
Below that I declare a property to hold my delegate
#property (nonatomic, strong) id<LocationTVSegueProtocol> makeSegueDelegate;
To actually trigger the segue i called the makeItSegueMethod on my makeSequeDelegate in my didSelectRowAtIndexPath method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
switch (indexPath.section) {
DLog(#"selected row %d",indexPath.row);
case dLocation:
{
if(indexPath.row == 2){
[_makeSegueDelegate makeItSegue:self];
} else if (indexPath.row == 7){
UIViewController Bit
and set up my UIViewController (named MultiTableHoldingVC) as implementing that protocol
#interface MultiTableHoldingView : UIViewController
<EnviroTVProtocol,LocationTVSegueProtocol> {
}
Below that i declared the protocol method in the list of my classes methods (although i'm not sure that is necessary as the compiler should know about the method as the decalration of implementing a protocol is essentially a promise to implement this method)
-(void) makeItSegue:(id)sender;
And then over in the implementation file of my UIViewController i wrote the method which essentially just calls preformSegueWithIdentifier
-(void) makeItSegue:(id)sender{
[self performSegueWithIdentifier:#"ChooseCountryNow"
sender:sender];
}
And to link it all together,as in the header file I had declared my instance of the tableView as follows
#property (strong, nonatomic) IBOutlet LocationTV *dsLocationTV;
I had to set that tables views delegate property to be self - which I did in my UIViewControllers -(void)ViewDidLoad method
_dsLocationTV.makeSegueDelegate = self;
It all seems a bit of a kludge calling a method to call a method and allprog suggestion is simpler (I cant for the life of me work out why it threw up errors for me) but this works just fine . Thanks to both allprog and danypata for their suggestions.
Hope this is helpful to someone out there
performSegueWithIdentifier: is a method of the UIViewController class. You cannot call it on a UITableView instance. Make your view controller implement the UITableViewDelegate protocol and set it as the delegate for the UITableView.
Another option is that you don't use segues. In the same delegate method do:
OtherViewController ov = [[OtherViewController alloc] init<<some initializer>>];
// Or in case of storyboard:
OtherViewController ov = [self.storyboard instantiateViewControllerWithIdentifier:#"ovidentifier"];
// push view controller
[self.navigationController pushViewController:ov animated:YES];
If the delegate object is different from the view controller, then the easiest solution is to add a weak property to the delegate's class that keeps a reference to the viewController, like this:
#property (weak) UIViewController *viewController;
and set it up in the viewDidLoad of the viewController
- (void) viewDidLoad {
self.tableView1.viewController = self;
}
Make sure that the tableView1 property is declared like this:
#property (IBACTION) (weak) SpecialTableView *tableView1;
Sometimes using the storyboard is more painful than writing the code yourself.

Resources