What method is called first when storyboard loads? - initialization

Using Xcode 4.2, in my application, a view loading is triggered by a segue event. What method will be called first inside a view controller?
-(void) viewWillAppear:(BOOL)animated works, but is it the first?
Initialization happens from the Storyboard it seems, init method is never manually called, upon object creation.
Let me clarify, when creating an instance of a class manually, we usually [[alloc]init] it first. [init] in this case, is the first method to be executed and a good place for various initializations.
What is the equivalent of init method when class instantiation happens via a segue event? In such a case, what method should contain all initialization logic?

I think the best option is -(void)awakeFromNib. This only occurs the once, whereas viewWillAppear and viewDidLoad etc could be called more than once after your initialisation.
UPDATE: As pointed out by Jean-Denis Muys below, -(id)initWithCoder:(NSCoder *)decoder is a better option for an initialiser that only gets called once as -(void)awakeFromNib has the potential to be called more than once.

According to Apple's View Controller Programming Guide,
When you create a view controller in a storyboard, the attributes you
configure in Interface Builder are serialized in an archive. Later,
when the view controller is instantiated, this archive is loaded into
memory and processed. The result is a set of objects whose attributes
match those you set in Interface Builder. The archive is loaded by
calling the view controller’s initWithCoder: method. Then, the
awakeFromNib method is called on any object that implements that method.
You use this method to perform any configuration steps that
require other objects to already be instantiated.

I would advise not to use awakeFromNib. I use simply both of these functions
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self setup];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
[self setup];
}
return self;
}
- (void)setupButton {
/* get ready to be called twice */
self.layer.cornerRadious = 10.0f;
}
because: let's say you subclassed UIButton. You must be ready for two scenario:
scenario 1. If you add the button programmatically --> initWithFrame->setupUI will be called
scenario 2. If you add the button using NIb --> initWithCoder->setupUI will be called.

Related

Refresh a form from class after insert()

I want refresh a form from a class. I want the refreh after a insert() statemant. Is here a better solution for this problem.
Here is my code:
try {
do {
row++;
this.readRow(row, cells);
ttsbegin;
this.insert();
ttscommit;
type = cells.item(row+1, 1).value().variantType();
}
while (type != COMVariantType::VT_EMPTY);
<--------
After the while the insert is finished and at this position where I will the refresh.
Usually you would pass a reference of the form's data source you want to refresh to your class and then call research on it to refresh it so that your newly inserted records appear.
Alternatively, although IMHO not that clean, is to pass a buffer of that form's data source to your class and then (maybe after checking via isFormDataSource) access and refresh the data source via the buffer's dataSource method.
A third way would be to implement a dedicated method on your form solely for the purpose of refreshing the data source as described above. When creating the instance of your class you then pass a reference to your form so that you can call that method when needed.
Update: To see how to call a method defined on a form from a class see the class Tutorial_Apply and form Tutorial_Form_Apply which shows how to call the method applyText which is implemented on the form. Likewise, you could define a method refreshData which calls research on your data source.

Getting ahold of the Application to call its method

In my Flex 4.5 application I have a TitleWindow Settings.mxml, which is popped up by the PopUpManager.
Once the user has changed some settings, I not only need to save them to a SharedObject, but also to apply them to the main Application itself - so that the changes are visible to the user immediately.
For example I need to call its method hideApp(somevalue);
The spark.components.Application does not seem to have any static/singleton methods to get ahold of it.
So how do you do it?
And I also wonder how to declare, that an MXML file implements one or several interfaces?
package {
public interface Hiddable {
function hideApp(value:Number):void;
}
}
I'm asking this, because besides the main Application I have a SettingsTest.mxml Application in my project for "unit testing" that particular functionality.
Thank you! Alex
Yes it does:
FlexGlobals.topLevelApplication
though I would recommend you use events to avoid tight coupling.
As for the question about interfaces: use the attribute implements
<s:Component ... implements="IClassA,IClassB" ... />
About implementing of interfaces in MXML components see the following documentation.
What about passing changed data back from your pop up window to the application I recommend you to use Observer pattern with Flash event model something like the following:
var myWindow:MyWindow = MyWindow(PopUpManager.createPopUp(this, MyWindow));
myWindow.addEventListener(MyWindowEvent.SUBMIT, myWindowSubmit);
private function myWindow(event:MyWindowEvent):void
{
// Unsubscribing from events
var myWindow:MyWindow = MyWindow(event.currentTarget);
myWindow.removeEventListener(MyWindowEvent.SUBMIT, myWindowSubmit);
// Changed data is passing with custom event object
someData = event.someData;
}
And you should implement your custom event for that (MyWindowEvent in my pseudo code) and fire it from your TitleWindow component. You can read more about implementing custom event in documentation.

How to implement callbacks in Java

I have a class called CommunicationManager which is responsible for communication with server.
It includes methods login() and onLoginResponse(). In case of user login the method login() has to be called and when the server responds the method onLoginResponse() is executed.
What I want to do is to bind actions with user interface. In the GUI class I created an instance of CommunicationManager called mCommunicationManager. From GUI class the login() method is simply called by the line
mCommunicationManager.login();
What I don't know how to do is binding the method from GUI class to onLoginResponse(). For example if the GUI class includes the method notifyUser() which displays the message received from theserver.
I would really appreciate if anyone could show how to bind methods in order to execute the method from GUI class (ex. GUI.notifyUser()) when the instance of the class mCommunicationManager receives the message from the server and the method CommunicationManager.onLoginResponse() is executed.
Thanks!
There's two patterns here I can see you using. One is the publish/subscribe or observer pattern mentioned by Pete. I think this is probably what you want, but seeing as the question mentions binding a method for later execution, I thought I should mention the Command pattern.
The Command pattern is basically a work-around for the fact that java does not treat methods (functions) as first class objects and it's thus impossible to pass them around. Instead, you create an interface that can be passed around and that encapsulates the necessary information about how to call the original method.
So for your example:
interface Command {
public void execute();
}
and you then pass in an instance of this command when you execute the login() function (untested, I always forget how to get anonymous classes right):
final GUI target = this;
command = new Command() {
#Override
public void execute() {
target.notifyUser();
}
};
mCommunicationManager.login(command);
And in the login() function (manager saves reference to command):
public void login() {
command.execute();
}
edit:
I should probably mention that, while this is the general explanation of how it works, in Java there is already some plumbing for this purpose, namely the ActionListener and related classes (actionPerformed() is basically the execute() in Command). These are mostly intended to be used with the AWT and/or Swing classes though, and thus have features specific to that use case.
The idiom used in Java to achieve callback behaviour is Listeners. Construct an interface with methods for the events you want, have a mechanism for registering listener object with the source of the events. When an event occurs, call the corresponding method on each registered listener. This is a common pattern for AWT and Swing events; for a randomly chosen example see FocusListener and the corresponding FocusEvent object.
Note that all the events in Java AWT and Swing inherit ultimately from EventObject, and the convention is to call the listener SomethingListener and the event SomethingEvent. Although you can get away with naming your code whatever you like, it's easier to maintain code which sticks with the conventions of the platform.
As far as I know Java does not support method binding or delegates like C# does.
You may have to implement this via Interfaces (e.g. like Command listener.).
Maybe this website will be helpful:
http://www.javaworld.com/javaworld/javatips/jw-javatip10.html
You can look at the swt-snippets (look at the listeners)
http://www.eclipse.org/swt/snippets/
or you use the runnable class , by overwritting the run method with your 'callback'-code when you create an instance

Best Practise to Define and update MXML component in Flex application

A Flex components values are initialized by init method.
In an application flow,
How to refresh a mxml component data value ; as init is called at the start up itself only.
Example of mxml component may be
as simple as button label or text
as complex as repeater whose data provider is a web service
( means a fresh quesy should be made to pull the data and refresh the dataprovider of repeater )
If the dataprovider is a collection or an array it will update itself as items are added to or deleted from the collection. You can listen to the CollectionEvent.CollectionChange event to see when a collection changes.
I'm not really sure what you mean though? Are you on about binding?
If you want to re-init the whole control, you could create an "reset" event and have the handler for the reset execute the same behavior as the init code.
That's the best I can do without more details...
you should create yourself setters and getters for the properties you want to modify and a refresh is required afterwards. for example:
private var _tmp : String = '';
public function set tmp(val : String) : void {
this._tmp = val;
this.doOtherDataRefreshNeeded();
}
public function get tmp() : String {
return this._tmp;
}
and this way, everytime the code that uses this component and needs to update it's tmp property. the setter will be called and in there a lot of other stuff can happen beside assigning the value.
for simple mxml components as texts and inputs, use bindings {} for their data values. those should update as soon as the data changes. if not, call .invalidateNow() method on them to force update.
use ValidateNow() method in mxml component in updating method

Implementing a WebControl factory in ASP.NET

I need to implement the classic Factory Method pattern in ASP.NET to create server controls dynamically.
The only way I've found to create .ascx controls is to use the LoadControl method of the Page/UserControl classes. I find it messy however to link my factory with a page or to pass a page parameter to the factory.
Does anybody know of another method to create such controls (such as a static method somewhere i'd have overlooked) ?
Thanks.
In the end, I decided to pass the page as a parameter to the factory. To make calls to the factory method easier, I changed the factory class from a singleton to a common class, and I passed the page to the constructor:
public ControlsFactory
{
private Page _containingPage;
public ControlsFactory(Page containingPage)
{
_containingPage = containingPage;
}
public CustomControlClass GetControl(string type)
{
... snip ...
CustomControlClass result = (CustomControlClass)_containingPage.LoadControl(controlLocation);
return result;
}
}
Since I have to instantiate many controls on each page with the factory, this is probably the most concise and usable way to implement the pattern.
Well after opening up reflector, the LoadControl function that is being used in Page is available in any TemplateControl.
Inside the actual LoadControl uses internal methods in BuildManager, so I don't think there's a way to use static methods without using reflection.
Well at least you don't need to pass a page around. Subclassing TemplateControl would work.

Resources