TiViewProxy and view creation - ios

I'm working on a titanium module.
Little bit confused about the TiViewProxy.
Why we are using -(void)setColor_:(id)color such methods (_ in methods) in ViewProxy ?
If we didn't write any such methods what happens when we call:
myModule.createView({
color : 'red'
});
If I didn't passed any argument on my createView() method how my view creation code will work on my module.
Means:
I'm just creating my view in my app.js like:
myModule.createView();
I'm handling the view creation code inside:
-(void)setColor_:(id)color
{
}
If I'm not passing any argument how my view is created ? Will it work ?

I'll explain the various moving parts. It's all part of the platform, so not critical that you know how it works. Knowing that it does this for you is important, though. So...
When you call myModule.createView(), the platform looks for a child of your module that matches certain constraints. Let me expand that statement by looking at the ti.pageflip module. myModule's class is TiPageflipModule. When I call myModule.createView(), the platform will look for TiPageflipViewProxy so it can instantiate it. TiPageflip comes from the module's name, minus "Module". "View" comes from createView. "Proxy" is tagged on because that's how we get from JavaScript to native. The TiPageflipViewProxy creates a native view, TiPageflipView. The proxy handles interactions between JavaScript and the native view. Make sense so far?
Part of the naming convention for exposed properties is that they are suffixed with an _. The platform looks for these methods, and calls each of them set in the creation dictionary createView({ whatever: 'value' }) as well as the property view.whatever = 'value'; or the method view.setWhatever('value'). (Search for the word "underscore" in the iOS mod dev guide, it only occurs once, to read more: https://wiki.appcelerator.org/display/guides/iOS+Module+Development+Guide).
Because you aren't defining createView, the platform is doing it for you, and it handles createView() just the same as createView({}). It's an optional param. That's just by definition.

Related

iOS: When to use delegate/dataSource (protocols) vs. properties

Many CocoaPod and native iOS libraries use protocols that they name either CustomClassDelegate or CustomClassDataSource as a means to do some setup or customization. I was wondering when I should use this programming model, because it seems like I could accomplish much of this with properties.
Example
If I define a custom class called SmurfViewController that has a SmurfLabel, is it better practice to store the smurfLabel as a private property and have a public computed property called smurf that looks like this:
private var smurfLabel = UILabel()
public var smurf: String {
get {
return smurfLabel.text
}
set(text) {
smurfLabel.text = text
}
}
or should I define a SmurfDataSource that has a public function that looks like this:
func textForSmurfLabel() -> String {
return "smurfText"
}
When should I use what here?
You should just use a property for that. Delegates and Datasources are for different controllers/Objects to speak to one another when the alternative is to instantiate the controller/object from the navigationStack/view hierarchy. A Delegate forms a specific communication between the two that allows for clear knowledge in what their relationship is while keeping them decoupled (assuming you try to keep it that way). I disagree with the article that says callbacks are "better". They are amazing and I advise using them often, but just understand that most options that swift provides you with have a place where they work best.
I might be slightly bias, but Swift is an amazing language with OOP being a backbone and everything it has was well put together in order to provide the correct tools for each situation you find yourself in.
I often find myself using both of those tools and one other more customizable option in my more advanced setups where I have an overseeing viewController that manages many child controllers. It has direct access to all of them that are active but if any of its children communicate with it, it is through delegates. Its main job is just to handle their place on the screen though, so I keep everything manageable.
Delegates and data sources are more appropriate for offloading behaviors to other entities, not simple values. In other words, if your type just needs a value for something, you are correct that it makes more sense to expose that as a property that can be set from the client code.
But what should happen (for example) when a user taps a specific table view cell is a behavior that shouldn't be hard coded into UITableView. Instead, for flexibility, any implementation of that behavior can be created in a delegate and called by the UITableView when appropriate.
In general, think of delegation as a way to make subclassing unnecessary, because the methods you would normally override in a subclass are instead moved into a protocol that can be implemented by ANY type, not just a subclass of the base type. And instead of calling internally implemented methods to get certain behaviors, your type is simply calling those behaviors on an external collaborating class (the delegate).
So perhaps the best guideline for when to use a data source or delegate is the question: "Would I need to subclass this class in order to change this value or behavior in the future". If the answer is no, because you can just set a property from client code, then don't use delegation. If the answer is yes, then offload that behavior to a delegate or data source instead of forcing future programmers to subclass your class to make it work for their use case.
Delegate is an interface for the undefined activities.
so when you make a SDK or framework, you must provide an interface so that users can write a proper code for the interfaces' expecting activity.
i.e, Table View needs a datasource to show it's contents, but the apple's library developers doesn't know the content whatever contents their library users will use. so they provided an interface like datasource, delegate.
and in the library, they just call this methods. that's the way the library should be made.
But in your code, the label is defined very explicitly as well as it's in the current view, and you don't need to make an interface for an undefined activity.
if you want know more about this kind of coding style, you need to do some researches on Software Design Pattern.
https://en.wikipedia.org/wiki/Observer_pattern
https://en.wikipedia.org/wiki/Delegation_pattern
https://en.wikipedia.org/wiki/Software_design_pattern
I love apple's sdk very much, because they used all the needed design patterns very properly.

Why do all methods have the same name in delegate?

i'm starting with Swift by developing a simple application with a tableView, a request to a server and a few things more. I realized that every method inside UITableViewDelegate protocol is named in the same way (i guess it might be the same with other protocols) and the differences are made by changing the parameters passed to those methods (which are called "tableView" by the way).
I was wondering why Apple would do something like this, as it's a bit messy when i try to implement method from this protocol, as i can't start typing "didSele..." just to autocomplete with "didSelectRowAtIndexPath"; instead i have to type "tableView" to get a list of all available methods and manually search for the one whose second parameter is "didSelectRowAtIndexPath".
Everything's working fine, but just trying to know WHY could this be done this way.
Thank you so much in advice :)
PS: There's a screenshot about what i'm saying:
Swift is designed to be compatible with Objective-C. After all, almost all existing OS X and iOS APIs are in Objective-C and C (with a bit of C++ code here and there). Swift needs to be able to use those APIs and thus support most Objective-C features one way or the other. One of the most important features of Objective-C is how method calls are made.
For example, in C, a function with 3 arguments is called like this:
foo(1, "bar", 3);
You don't know what the arguments are supposed to be. So in Objective-C, the arguments are interleaved with the method name. For example, a method's name might be fooWithNumber:someString:anotherNumber: and it would be called like:
[anObject fooWithNumber:1 someString:#"bar" anotherNumber:3];
Swift now tries to be compatible with this Objective-C feature. It thus supports a form of named arguments. The call in Swift would look like:
anObject.foo(number:1, someString:#"bar", anotherNumber:3)
Often Swift method definitions are written so that you don't need to explicitly name the first argument, like:
anObject.foo(1, someString:#"bar", anotherNumber:3)
If you look up the UITableViewDelegate protocol documentation and select Objective-C you can see that all of these methods start with tableView: to designate the sender, but from then on they are very different. The list you've cited is the result of the conversion from Objective-C to Swift naming convention.
It is just naming conventions. It is the same in Objective-C. You can have a look to this page. Without these conventions it would be a complete mess.
The method name is not only the first word but also the public names of the parameters.
E.g. it the method name is not tableView() but tableView(_:didSelectRowAtIndexPath:).

Accessing hidden private class in Objective-C

How can I access an attribute that's been hidden via:
__attribute__((visibility("hidden")))
I'm trying to access UINavigationItemButtonView, but it seems sometime recent (iOS 7.1?) they've added the above into the header file. Recursively printing the window no longer reveals UINavigationItemButtonView in the view stack either.
So, given a UINavigationBar, how can I access a UINavigationItemButtonView that has been hidden via the above flag?
Printing all the subviews in UINavigationBar doesn't reveal it.
The attribute keyword is simply a message to the compiler, and has nothing to do with the runtime. Using ((visibility("xxx")) only serves to tell the compiler if the given declaration should be "visible" or usable by clients in some other package. visibility("hidden") just means that, despite the public declaration, make this thing invisible to external packages, so that they will not be able to use it. Compiling will fail if you attempt to use this class or method.
If you don't see this class being used in a recursive description, it is likely that this class is no longer used; it certainly isn't because of the attribute statement.
Since it's a private class, you shouldn't. Anything you do to bypass that restriction may result in your application failing the review process. Not to mention that, in general, accessing private and/or hidden API's, classes, instance variables, properties or whatever else it is, is a really good way to make sure your application breaks in the (not too distant) future.

Using Dart as a DSL

I am trying to use Dart to tersely define entities in an application, following the idiom of code = configuration. Since I will be defining many entities, I'd like to keep the code as trim and concise and readable as possible.
In an effort to keep boilerplate as close to 0 lines as possible, I recently wrote some code like this:
// man.dart
part of entity_component_framework;
var _man = entity('man', (entityBuilder) {
entityBuilder.add([TopHat, CrookedTeeth]);
})
// test.dart
part of entity_component_framework;
var man = EntityBuilder.entities['man']; // null, since _man wasn't ever accessed.
The entity method associates the entityBuilder passed into the function with a name ('man' in this case). var _man exists because only variable assignments can be top-level in Dart. This seems to be the most concise way possible to use Dart as a DSL.
One thing I wasn't counting on, though, is lazy initialization. If I never access _man -- and I had no intention to, since the entity function neatly stored all the relevant information I required in another data structure -- then the entity function is never run. This is a feature, not a bug.
So, what's the cleanest way of using Dart as a DSL given the lazy initialization restriction?
So, as you point out, it's a feature that Dart doesn't run any code until it's told to. So if you want something to happen, you need to do it in code that runs. Some possibilities
Put your calls to entity() inside the main() function. I assume you don't want to do that, and probably that you want people to be able to add more of these in additional files without modifying the originals.
If you're willing to incur the overhead of mirrors, which is probably not that much if they're confined to this library, use them to find all the top-level variables in that library and access them. Or define them as functions or getters. But I assume that you like the property that variables are automatically one-shot. You'd want to use a MirrorsUsed annotation.
A variation on that would be to use annotations to mark the things you want to be initialized. Though this is similar in that you'd have to iterate over the annotated things, which I think would also require mirrors.

Where to put needed initialization code when using Dependency Injection?

When my constructors are pure arguments-to-propeties setters then I'm not sure where to put other code that a class needs to properly work.
For example in JavaScript I'm programming a WindowMessageController that processes message events on the window object.
In order for this to work, I must somewhere attach the handler:
var controller = this;
this.applicableWindow.addEventListener("message", function(event) {
controller.messageAction(event.data);
}
Where does this stuff correctly belongs?
in the constructor
in the .initialize() method - introduces temporal coupling
in the WindowMessageControllerFactory.create(applicableWindow) - quite a distant place for so central piece of code. This means that even such a small class would be split into two pieces.
in the composition root itself - this would multiply its size when doing all the time
in some other class WindowMessageRouter that would have only one method, the constructor, with this code
EDIT
This case seems special because there is usually only one instance of such a controller in an app. However in more generalized case what would be the answer if I was creating an instances of Button class that would wrap over some DOM <button /> element? Suddeny a
button = buttonFactory.create(domButtonEl);
seems much more useful.
Do not put any real work into constructors. Constructors are hardly mockable. Remember, seams aka methods are mockable. Constructor are not mockable because inheritance and mocking.
Initialize is a forbidden word, to much general.
Maybe, but you can implement factory as a static method of class too, if you are scared of many classes ,)
Composition root is just an ordinary factory. Except it is only one, because your app probably have just one entry point ,)
Common, we are using Javascript. If you need just one factory method, why you need class for it? Remember, functions are first class objects.
And for edit. There is nothing special on singetons, unless they do NOT control own lifecycle.
Golden rule: Always (almost ,) do separation between app wiring and app logic. Factories are wiring. Just wiring, no logic, therefore nothing to test.
I would place this code into initialize(window) method but this method cannot be part of WindowMessageController's public API - it must be visible and called by direct users (so composition root and tests) only.
So when DI container is returning WindowMessageController instance then it is container's responsibility that initialize method has been called.
Reply to EDIT: Yes, this factory seems to be the best way for me. Btw. don't forget that the factory should probably have a dispose method (i.e. unbinds the event handler in case of button)...
I think you need to create a Router class that will be responsible for events distribution. This Router should subscribe to all the events and distribute them among the controllers. It can use some kind of the message-controller map, injected into constructor.

Resources