Objective C repeated callback required - ios

I'm quite new to iOS development, and I've been trying to solve the following problem:
I have a ViewController displaying information that changes with time. I have another controller (TimeController) managing time. TimeController has an NSTimer firing every second to check whether I've entered a new time slot (there's some logic behind it, and if I've entered a new time slot that means that the information in the ViewController needs to be updated.
In my understanding, I need some kind of callback procedure but I couldn't figure out how to do it - I read about blocks but to be honest they're quite overwhelming and I couldn't relate my problem to the examples I saw.
The TimeController looks something like the following:
// TimeController.h
#interface TimeController : NSObject
#property (weak) NSTimer *periodicTimer;
#property NSInteger timeslot;
#end
// TimeController.m
#import "TimeController.h"
#implementation TimeController
-(void)startTimer {
self.periodicTimer = [NSTimer scheduledTimerWithTimeInterval:(1) target:self
selector:#selector(onTimer) userInfo:nil repeats:YES];
}
-(void)onTimer {
// check if anything has changed.
// If so, change timeslot. Notify "listening" objects.
}
In a simple example with a single ViewController depending on TimeController, I'm imagining something like this:
// ViewController.h
#interface ViewController : UIViewController
#property TimeController* timeCtrl;
#end
// ViewController.m
#import "ViewController.h"
#import "TimeController.h"
-(void)onNotificationFromTimeController {
// timeslot has changed in the TimeController.
NSInteger tslot = timeCtrl.timeslot;
// figure out new display value depending on tslot. Update the view
}
What's missing here (among other stuff like proper initialisation of timeCtrl) are the callback mechanisms. I'd appreciate any help on this!

Notifications
Add a listener to the event (let's call it "TimeNotificationEvent") in ViewController:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(onNotificationFromTimeController) name:#"TimeNotificationEvent" object:nil];
In the onTimer method in TimeController.m, add the following code to post a notification:
[[NSNotificationCenter defaultCenter] postNotificationName:#"TimeNotificationEvent" object:nil];
Sidenote: To stop listening for notifications:
[[NSNotificationCenter defaultCenter] removeObserver:self name:#"TimeNotificationEvent" object:nil];
Easy to setup
You can have multiple listeners for the same event
Blocks
Add a property in TimeController.h:
#property (nonatomic, copy) dispatch_block_t timerBlock;
Add a call to the timerBlock in TimeController.m:
-(void)onTimer {
// Check for nil to avoid crash
if (_timerBlock) {
_timerBlock();
}
}
Assign the block in ViewController:
_timeCtrl.timerBlock = ^{
// Do stuff to the UI here
};
A bit more complex (retain cycles, syntax etc)
Only one listener (with this particular example implementation)
Easier to follow the code

Related

Refreshing background view from modal view

I want to update the view controller that is covered with a modal view in my application, I'm using swift. What I have currently is this:
The view on the right is the caller, and the views on the left are the modal views triggered by each button from the first one. They do basic edit, add new operations. These views are modally presented over the main one, and what I want to do is update the table view controllers enbedded in the two containers once I save the data from one of the modals.
I researched the use of one of the viewLoad events, but I'm kinda stuck at the moment. How can I do this?
Well you can do it in two ways
1. Delegate
2. NSNotificationCenter
In your Model class.h file
#protocol someProtoColName<NSObject>
-(void)finishedDoingMyStuff;
#end
#interface ModelClass()
#property (nonatomic,weak) id<someProtoColName> delegateObj;
Then in your ModelClass.m
-(void)someactionHappend{
//this is the method where you save your things call the delegate method inside here like this.
[self.delegateObj finishedDoingMyStuff];
}
Then in your CallerClass.h
#import ModelClass.h
#interface CallerClass:UIViewController<someProtoColName>
Inside CallerClass.m viewDidLoad
-(void)viewDidLoad{
ModelClass *model = [[ModelClass alloc]init];
model.delegateObj = self;
}
//Now declare the delegate method
-(void)finishedDoingMyStuff{
//update your code that this has happend. this will be called when your model class's button action inside which you sent the `self.delegateObj`message is invoked instantaneously.
}
NSNotificationCenter
CallerClass.m
-(void)viewDidLoad{
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(someMethod) name:#"NOTIFICATIONNAME" object:nil];
}
-(void)dealloc{
[[NSNotificationCenter defaultCenter]removeObserver:self name:#"NOTIFICATIONNAME" object:nil];
}
-(void)someMethod{
//something has happened, do your stuff
}
And in each of the Model class (if they are many or one dsnt matter)|
ModelClass.m
-(void)someactionHappend{
//this is your action method that you want to do stuff in the model
[[NSNotificationCenter defaultCenter] postNotificationName:#"NOTIFICATIONNAME" object:nil userInfo:nil];
}
Hope this helps you out.

Passing information back from UITableViewDataSource to ViewController

I have a ViewController with a UITableView. As I wanted to split out the data handling I created an own class that answers UITableViewDataSource.
This class is supposed to first fetch data from CoreData and afterwards from a REST API.
How can the DataSource talk back to the ViewController to tell it to call reloadData on the TableView?
What's the best practice here?
I thought about:
KVO the DataSource's data and when the array change call reloadData
Handing over a block (with [self.table reloadData]) to the DataSource which gets executed every time the data changes in the DataSource
Make the table property public on the ViewController so the DataSource could call reloadData (which I don't really like as an idea)
Have a property on the DataSource which holds the ViewController with the Table to use it as a delegate (which sounds to me like a loop)
Are there any smart ways to do it? Or even common practice how to solve this?
Update:
I'm less interested in code how to do implement a certain design pattern. I'm more interested in the reasoning why to chose one pattern over the other.
Without more details, it sounds like you need a callback here. There are several methods that will work. If you have a 1 to 1 relationship (meaning your dataSource only needs to talk to the VC), then this is a good case for either:
1.) A delegate. Create your own delegate protocol for your dataSource and then have the VC adhere to that protocol (be the delegate).
2.) Do the same thing just using a block for a callback.
KVO will work just fine as well, but the above two are more in line with your scenario.
You could add a tableView property to your custom data source but that then blurs the lines of why you created that class in the first place.
For situations like this, I prefer delegates.
#class CupcakePan;
#protocol CupcakePanDelegate <NSObject>
- (void)cupcakesAreReadyForPan:(CupcakePan *)pan;
#end
#interface CupcakePan : NSObject <UITableViewDataSource>
#property (weak) id<CupcakePanDelegate> delegate;
#end
#implementation CupcakePan
- (void)bakingComplete {
[self.delegate cupcakesAreReadyForPan:self];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [cupcakes count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
return [make a CupcakeCell];
}
#end
#interface CupcakeViewController <CupcakePanDelegate>
#end
#implementation CupcakeViewController
- (void)cupcakesAreReadyForPan:(CupcakePan *)pan {
[_tableView reloadData];
}
#end
I frequently use NSNotificationCenter for these types of interactions.
In your datasource write the following code:
#define ABCNotificationName #"ABCNotificationName"
#define ABCNotificationData #"ABCNotificationData"
// ...
[[NSNotificationCenter defaultCenter] postNotificationName:ABCNotificationName object:self userInfo:#{ ABCNotificationData: data }];
In your view controller do the following:
-(void)loadView {
// setup your view
[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(datasourceUpdated:) name:ABCNotificationName object:dataSource];
}
-(void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)dataSourceUpdated:(NSNotification*)notification {
id data = notification.userInfo[ABCNotificationData];
// respond to the event
[self.tableView reloadData];
}
Note, that if you don't have any piece of data to communicate back to the controller it becomes even easier. In your datasource write the following code:
#define ABCNotificationName #"ABCNotificationName"
// ...
[[NSNotificationCenter defaultCenter] postNotificationName:ABCNotificationName object:self];
In your view controller do the following:
-(void)loadView {
// setup your view
[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(datasourceUpdated) name:ABCNotificationName object:dataSource];
}
-(void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)dataSourceUpdated {
// respond to the event
[self.tableView reloadData];
}

How to access instance from another class

Thanks for your help in advance!
I'm new to OOP, so this problem may be really basic, but I've searched for hours and still cannot find a good solution.
I'm using Cocos2d and Box2d in the project. In my GameLayer.mm file, I have a label to show current score. And there's is a custom sprite derived from CCSprite.
Now, I wanna increment current score from my custom sprite class when the property of sprite "isDead" is changed to true. As follows:
- (void) setIsDead
{
isDead = 1;
// then increment score
}
My question is how I can increment score from this subclass? I cannot access the instance or instance method of GameLayer.mm from this subclass. I tried to change the function of incrementing score from instance method to class method, and make score as a global instance, but I got duplicate error later.
Thanks for any advice!
Here is another approach I like: delegates.
First, go to your custom CCSprite header and create a new protocol. Basically, add this:
#protocol MyCustomDelegate
-(void)spriteGotKilled:(CCSprite*)sprite;
#end
Next, you need to modify your custom CCSprite to store its delegate. Your interface would look like this:
#interface MySprite {
id delegate;
}
#property (retain,nonatomic) id delegate;
Now go to GameLayer.h and make it implement the protocol:
#interface GameLayer : CCLayer <MyCustomDelegate>
Next implement the protocol method in your layer:
-(void)spriteGotKilled:(CCSprite*)sprite {
NSLog(#"%# got killed!",sprite);
}
And, finally, go to your setIsDead method:
-(void)setIsDead {
isDead = 1;
// Check if we have a delegate set:
if ([self delegate] != nil) {
// Check if our delegate responds to the method we want to call:
if ([[self delegate]respondsToSelector:#selector(spriteGotKilled:)]) {
// Call the method:
[[self delegate]spriteGotKilled:self];
}
}
}
When you create your sprite, you must set the layer as its delegate. Something like this:
MySprite *sprite = [[MySprite alloc]init];
[sprite setDelegate:self];
Now whenever your sprite dies, spriteGotKilled will be called in your layer.
You could use The Observer Design Pattern here in which an observer listens to an event and performs an action accordingly.
So in your GameLayer.mm add the observer in the init function:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(receiveIsDeadNotification:)
name:#"SpriteIsDeadNotification"
object:nil];
and add a function:
- (void) receiveIsDeadNotification:(NSNotification *) notification
{
if ([[notification name] isEqualToString:#"SpriteIsDeadNotification"])
//update your label here
}
and in your custom sprite ,add the following line in the setIsDead method
-(void) setIsDead{
isDead =1;
[[NSNotificationCenter defaultCenter]
postNotificationName:#"SpriteIsDeadNotification"
object:self];
}
also remember to remove the observer in the dealloc of GameLayer.mm
[[NSNotificationCenter defaultCenter] removeObserver:self];
This pattern will reduce coupling in your code as instances of one class are not trying to access the methods of another.

Copying of NSMutableArray from one viewcontroller to another viewcontroller?

I have one NSMutableArray in FirstViewController declared as firstArray.
I want to copy the secondArray into firstArray.
In the SecondViewController,
Self.FirstViewController.firstArray = self.secondArray;
When I attempt to NSLog the firstArray.count from the FirstViewController, it display 0. It should have two objects in the array
Anyone can advise on this?
You can choose one of this solutions:
Singleton
Passing Data between ViewControllers
Delegation
You can find all the info you need right here: https://stackoverflow.com/a/9736559/1578927
Singleton example:
static MySingleton *sharedSingleton;
+ (void)initialize
{
static BOOL initialized = NO;
if(!initialized)
{
initialized = YES;
sharedSingleton = [[MySingleton alloc] init];
}
}
It looks like either the second array has already been deallocated when passing the reference to the first view controller, or the first view controller itself has already been nilled out. If the first is true, then you may need a different model object to hold your data rather than persisting it in the controller layer of your app. If that is not the case, then you may want to consider a direct copy. The easiest way of doing this is to declare the firstArray property as the keyword copy rather than strong in your interface file.
If you do need to persist the data in the model layer of your app, a singleton pattern object would indeed be one way of achieving this as EXEC_BAD_ACCESS (nice name!) points out. A slightly more modern (though functionally equivalent) way of writing a singleton is as follows.
#interface MySingleton : NSObject
#property (strong, readwrite) id myData;
+ (id)sharedSingleton
#end
#implementation MySingleton
+ (id)sharedSingleton
{
static MySingleton *singleton = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
singleton = [[MySingleton alloc] init];
// Do other setup code here.
});
return singleton;
}
#end
Note the use of dispatch_once - this makes certain that the static singleton can only be created once (whereas technically, you can invoke +[NSObject initialize] as many times as you feel like manually, though I'd never advise doing so).
You may also take advantage of NSNotificationCenter
SecondViewController.m
[[NSNotificationCenter defaultCenter] postNotificationName:#"arrayFromSecondVC" object:secondArray];
FirstViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(populateArray:) name:#"arrayFromSecondVC" object:nil];
}
-(void)populateArray:(NSNotification *)notif
{
self.firstArray = [notif object];
}
And remove the notification when the viewUnload or didRecieveMemoryWarning method.
Hope it helps.

How to pass data to parent view IOS

I know this question is asked once every two days. I can not see what I am doing wrong though.
I have a storyboard navigation controller based app.
My notification and pop / push segues works well, only thing is I can not add string to parents view NSmutablearray.
I want to add a string object to parent view's nsmutablearray. My decent code does not pass any data.
parent.h
#interface CreaatePlistTableViewController : UITableViewController<UITableViewDelegate, UITableViewDataSource>{
NSMutableArray *presenterList;
}
#property (nonatomic, strong) NSMutableArray *presenterList;
parent.m
NSString * const NOTIF_CreatePlist_UpdateTableview= #"CreatePlist/UpdateTableview";
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Private interface definitions for update tableview
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
#interface CreaatePlistTableViewController (private)
- (void)CreatePlistUpdateTableview:(NSNotification *)notif;
#end
#implementation CreaatePlistTableViewController
#synthesize presenterList=_presenterList;
- (void)viewDidLoad
{
[super viewDidLoad];
_presenterList=[[NSMutableArray alloc] init];
// Register observer to be called when logging out
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(CreatePlistUpdateTableview:)
name:NOTIF_CreatePlist_UpdateTableview object:nil];
NSLog(#"Presenter List: %#", _presenterList);
}
- (void)CreatePlistUpdateTableview:(NSNotification *)notif{
NSLog(#"Notification recieved");
NSLog(#"Presenter List: %#", _presenterList);
[_createPlistTableview reloadData];
}
child.h
#interface AddPresenterViewController : UITableViewController<UITextFieldDelegate,UIAlertViewDelegate>{
CreaatePlistTableViewController *crereaatePlistTableViewController;
}
#property(nonatomic,strong) CreaatePlistTableViewController *crereaatePlistTableViewController;
child.m
#synthesize crereaatePlistTableViewController=_crereaatePlistTableViewController;
//finished adding presenter
-(IBAction)finishedAddingPresenter:(id)sender{
//some xml string here
NSLog(#"final result XML:\n%#", writer.XMLString);
_crereaatePlistTableViewController=[[CreaatePlistTableViewController alloc]init];
//add object to parents view data source
[_crereaatePlistTableViewController.presenterList addObject:writer.XMLString];
//dismiss the view
[self.navigationController popViewControllerAnimated:YES];
//notify the parent view to update its tableview
[[NSNotificationCenter defaultCenter] postNotificationName:#"CreatePlist/UpdateTableview" object:nil];
}
Output
Notification recieved
Presenter List: (
)
So notification works when I click the button. But it does not pass object to nsmutablearray.
What I am doing wrong here ? How can I add an object to parent view's nsmutablearray?
It seems everything is good except your alloc of parent view object I am not that familiar with storyboard but You said you are using navigation navigation controller
so change this
_crereaatePlistTableViewController=[[CreaatePlistTableViewController alloc]init];
to
_crereaatePlistTableViewController= [self.navigationController.viewControllers objectAtIndex:0];
It may work I am not sure
You wrote this.
[_crereaatePlistTableViewController.presenterList addObject:writer.XMLString];
Do you ever initialize the array? No. Use the debugger and you will see that at this line the presenterList is nil.
Now as a point of style. Avoid using NSNotificationCenter to pass data or signaling other objects. #TheRonin gave a handy link. You should also look into some tutorials on Segues, because these are solved problems.
This is another related post that you might find interesting.

Resources