Is there anyway to add more fields (e.g. location and etc) to TTPhoto protocol?
I know that one way is to create my own protocol but that would require me to change a lot of stuffs in my view controllers. Is there any simpler way to achieve this?
Formal protocols are primarily a compile time conceit, to help you be more clear about your intentions. They're a relatively recent invention, before which all protocols were informal — they were part of the class documentation but not declared in the code. They have a runtime effect in that you can use some of the Objective-C runtime methods to query whether a particular class responds to a particular protocol (just as you can query whether a particular class responds to a particular selector), but no such testing will occur at runtime when you pass objects about.
Protocols are just a contract defining communications and don't specify behaviour. So there's no concept of inheritance. And there's no runtime list of the selectors included in a protocol, so the idea isn't particularly helpful.
Your best shot is to define an additional protocol that includes the extra functionality you want. Write your new objects to implement both protocols. Extend classes you don't want or have access to using category methods.
If you need additional storage to handle the new fields, then it's safest to subclass. You can actually add instance variables at runtime nowadays, but you'd need to drop down to the C interface to the Objective-C runtime and finding an opportunity to do so would require some hoop jumping.
Related
Is it possible to pass parameters to a Singleton class? If so how?
This is a snippet of one of my Singleton classes:
class NotificationManager: NSObject {
static let sharedManager = NotificationManager()
var tabBarController: UITabBarController!
private override init() {
super.init()
}
In the case of this Singleton, the public property tabBarController must always be set before being used.
I'm wondering if its possible to pass the correct UITabBarcontroller object on start up, as I assume this is when my Singleton class is being instantiated? This would prevent the class from ever being implemented incorrectly. Not that I ever expect this to be a problem as is.
Also, is it perfectly fine to use Singleton classes in this instance? To manage a specific set of operations? In the past I was always passing objects around, especially managedObjectContext, however now I've found Singleton classes to make everything much cleaner, nicer, and safer (as there is only ever one stance) in large apps. I can understand passing objects between classes is fine for smaller apps, but once they can large it can get pretty messy.
In my most recent app I'm also using a shared Singleton class between my iOS and watchOS app that defines a few global variables, such as server endpoints, and environments. This appears to be the best way to go about defining variables that require this access.
I've had friends tell me that Singletons are bad to use, and from what I've Google'd, it really seems like a mixed bag. In my case, they have made my code way easier to manage, and handle.
Thanks.
You can set up a singleton anyway you like. You will just have to change the way it's initialized/organized. There are some examples in this question. For some general critiques of the pattern you can read here
My own opinion is that it's generally good to avoid singletons, but sometimes they are necessary. However I tend to say singletons should only be used when the can be initialized when the app starts (App Delegate), and can/should be used and alive throughout the entire app's lifetime.
I would warn against using singletons having to do with your user interface. It appears you're capture a UITabBarController. I would strongly recommend against this, and instead use delegation or Notifications to respond to events. This is partially because of general design weirdness, but it also complicates app restoration and the memory footprint of your app.
I'm thinking about a platform-neutral (i.e. not .NET MEF) technique of implementing chain-of-responsibliity pattern using web services as the handlers. I want to be able to add more CoR handlers by deploying new services and not compiling new CoR code, just change configuration info. It seems the challenge will be managing the metadata about available handlers and ensuring the handlers are conforming to the interface.
My question: any ideas on how I can safely ensure:
1. The web services are implementing the interface
2. The web services are implementing the base class behavior, like calling the successor
Because, in compiled code, I can have type-safety and therefore know that any handlers have derived from the abstract base class that ensures the interface and behavior I want. That seems to be missing in the world of services.
This seems like a valid question, but a rather simple one.
You are still afforded the protection of the typing system, even if you are loading code later, at runtime, that the original code never saw before.
I would think the preferred approach here would be to have something like a properties file with a list of implementers (your chain). Then in the code, you are going to have to have a way to instantiate an instance of each handler at runtime to construct the chain. When you construct the instance, you will have to check its type. In Java, for instance, that would take the form of instanceof (abomination ordinarily, but you get a pass for loading scenarios), or isAssignableFrom. In Objective C, it's conformsToProtocol.
If it doesn't, it can't be used and you can spit an error out to the console.
I was wondering what the relative advantages of using custom protocols and delegates are when compared to other techniques for achieving bi-directional class communication?
Another solution for example is to have the following:
A associated to B
B associated to A
This way both A and B have access to each others information...
I kind of get an understanding that protocols allow for an increase in the modularity of the system design, but I'm not entirely sure why or how?
Custom delegate protocol is a great thing, it allows your object to not depend on the particular class. Any object that conforms to the given protocol can be the delegate. For example, any object can be the delegate for the table view if it implements NSTableViewDelegate protocol.
Otherwise, if you use direct association, you have to use object of the certain class.
With the delegate pattern (specifically the use of a protocol) the classes stay loosely coupled. This is significant when considering the MVC pattern. Delegate pattern allows the view to stay decoupled from the controller.
Also, "A associated to B B associated to A" would create a retain cycle. The delegate pattern codifies the memory management issues (i.e. a class should not retain its delegate).
This kind of bi-directional dependency is to avoid as at compilation level it mean that you have each include including the other's.
You are tying your classes too much when one the goal of OO programming is to reduce component coupling.
Even if you can do it doesn't mean it's good practice.
Good pratice would be to specify 2 protocols, one for for the server/object/producer/... and one for the client/delegate/consumer/...
Then A would implement one protocol, would talk to object implementing the second one.
B would implement second protocol.
In the end that mean you can replace B implementation in the future to match a new API/programming model/test-stub, etc.
Reduce coupling is a mean to help modulartity and testability of your code.
You don't have to, but you'll be happy when coming back on your code 6 month later from now :)
Usually there is no need for 2 objects to have a full bi-directional communication.
Usually in iPhone you initiate B from A (e.g. detailed view controller from a list view controller) and set A to be B's delegate so that it will receive direct notification on relevant events.
It is not right in terms of object oriented design/programming to connect 2 objects in a fully bi-directional connection.
You loose the encapsulation in this case.
Once you use the delegation design pattern your object don't really know each other but still can communicate.
In addition, this way any object that implements a certain protocol may be set as a delegate.
This way the objects also don't have to retain each other...
I recently read about Dynamic Creation as one of the design pattern in Cocoa. However, I don't really understand how it works. So I need clarification from you who have implemented in your design.
What is it? Why and when would you use this design pattern?
I have read that you use NSClassFromString() to access the class. I assume that I use this when I want to use class that doesn't exist within the project I'm working on. Usually when I want to use certain class, I imported them in header. Does using this approach skip the #import process?
Class JavaArrayList = NSClassFromString(#"java.util.ArrayList");
I quote the code above as example. If do according to the code above, that means I can create a new JavaArrayList class and use the methods in it right?
JavaArrayList *foo = [[JavaArrayList alloc] init];
[foo useMethodBelongJava:doWhateverTask];
What are the benefits of using this design pattern? Especially in iPhone Development.
Your example appears to be using that pattern to instantiate a Java class. In the old days (up to about MacOS 10.4 I think), Apple had some technology called the Cocoa-Java Bridge, which let you use Java classes within Objective-C code. You had to instantiate them in the manner specified, because they didn't have Objective-C header files to import.
However, as of Snow Leopard, the Java Bridge no longer exists, so the code in your question won't work any more.
The recommended solution for calling a Java class from Objective-C is now JNI. Take a look at this question if that is what you're trying to do.
What is it? Why and when would you use this design pattern?
Coming back to NSClassFromString, it has other uses besides instantiating Java classes (which, as I mentioned, it doesn't do any more!). For an example, recently I wrote a library for parsing the response from a web service. In order to make it work with different web services, I had it read in a configuration file that described the data format it was expecting. For each field in the web service, my configuration file specified which Cocoa class to instantiate. Thus, in my code, I had a Cocoa class name as a string. To instantiate the object I wanted, I used NSClassFromString to turn it into a Class object.
Usually when I want to use certain class, I imported them in header. Does using this approach skip the #import process?
It can do. NSClassFromString will instantiate any class that is present at run time, so you don't need the header to be able to use it. If you don't have the header, you'll get a bunch of warnings of "may not respond to selector" whenever you try and use your newly instantiated class, as the compiler doesn't have enough information to be helpful. However, in many circumstances where NSClassFromString is useful, the header files aren't available.
See this link:
need advise about NSClassFromString
The only real benefit for iPhone was being able to reference classes from newer APIs and still target the old APIs. Since 4.0 you can do this anyway by setting the deployment target of your project. I can't really see any reason you would use it for iPhone programming any more.
This would only work for objective-C classes. You can't import java objects into your iphone app.
Seems like everyone is moving towards IoC containers. I've tried to "grok" it for a while, and as much as I don't want to be the one driver to go the wrong way on the highway, it still doesn't pass the test of common sense to me. Let me explain, and please correct/enlighten me if my arguments are flawed:
My understanding: IoC containers are supposed to make your life easier when combining different components. This is done through either a) constructor injection, b) setter injection and c) interface injection. These are then "wired up" programmatically or in a file that's read by the container. Components then get summoned by name and then cast manually whenever needed.
What I don't get:
EDIT: (Better phrasing)
Why use an opaque container that's not idiomatic to the language, when you can "wire up" the application in (imho) a much clearer way if the components were properly designed (using IoC patterns, loose-coupling)? How does this "managed code" gain non-trivial functionality? (I've heard some mentions to life-cycle management, but I don't necessarily understand how this is any better/faster than do-it-yourself.)
ORIGINAL:
Why go to all the lengths of storing the components in a container, "wiring them up" in ways that aren't idiomatic to the language, using things equivalent to "goto labels" when you call up components by name, and then losing many of the safety benefits of a statically-typed language by manual casting, when you'd get the equivalent functionality by not doing it, and instead using all the cool features of abstraction given by modern OO languages, e.g. programming to an interface? I mean, the parts that actually need to use the component at hand have to know they are using it in any case, and here you'd be doing the "wiring" using the most natural, idiomatic way - programming!
There are certainly people who think that DI Containers add no benefit, and the question is valid. If you look at it purely from an object composition angle, the benefit of a container may seem negligible. Any third party can connect loosely coupled components.
However, once you move beyond toy scenarios you should realize that the third party that connects collaborators must take on more that the simple responsibility of composition. There may also be decommissioning concerns to prevent resource leaks. As the composer is the only party that knows whether a given instance was shared or private, it must also take on the role of doing lifetime management.
When you start combining various instance scopes, using a combination of shared and private services, and perhaps even scoping some services to a particular context (such as a web request), things become complex. It's certainly possible to write all that code with poor man's DI, but it doesn't add any business value - it's pure infrastructure.
Such infrastructure code constitutes a Generic Subdomain, so it's very natural to create a reusable library to address such concerns. That's exactly what a DI Container is.
BTW, most containers I know don't use names to wire themselves - they use Auto-wiring, which combines the static information from Constructor Injection with the container's configuration of mappings from interfaces to concrete classes. In short, containers natively understand those patterns.
A DI Container is not required for DI - it's just damned helpful.
A more detailed treatment can be found in the article When to use a DI Container.
I'm sure there's a lot to be said on the subject, and hopefully I'll edit this answer to add more later (and hopefully more people will add more answers and insights), but just a couple quick points to your post...
Using an IoC container is a subset of inversion of control, not the whole thing. You can use inversion of control as a design construct without relying on an IoC container framework. At its simplest, inversion of control can be stated in this context as "supply, don't instantiate." As long as your objects aren't internally depending on implementations of other objects, and are instead requiring that instantiated implementations be supplied to them, then you're using inversion of control. Even if you're not using an IoC container framework.
To your point on programming to an interface... I'm not sure what your experience with IoC containers has been (my personal favorite is StructureMap), but you definitely program to an interface with IoC. The whole idea, at least in how I've used it, is that you separate your interfaces (your types) from your implementations (your injected classes). The code which relies on the interfaces is programmed only to those, and the implementations of those interfaces are injected when needed.
For example, you can have an IFooRepository which returns from a data store instances of type Foo. All of your code which needs those instances gets them from a supplied object of type IFooRepository. Elsewhere, you create an implementation of FooRepository and configure your IoC to supply that anywhere an IFooRepository is needed. This implementation can get them from a database, from an XML file, from an external service, etc. Doesn't matter where. That control has been inverted. Your code which uses objects of type Foo doesn't care where they come from.
The obvious benefit is that you can swap out that implementation any time you want. You can replace it with a test version, change versions based on environment, etc. But keep in mind that you also don't need to have such a 1-to-1 ratio of interfaces to implementations at any given time.
For example, I once used a code generating tool at a previous job which spit out tons and tons of DAL code into a single class. Breaking it apart would have been a pain, but what wasn't much of a pain was to configure it to spit it all out in specific method/property names. So I wrote a bunch of interfaces for my repositories and generated this one class which implemented all of them. For that generated class, it was ugly. But the rest of my application didn't care because it saw each interface as its own type. The IoC container just supplied that same class for each one.
We were able to get up and running quickly with this and nobody was waiting on the DAL development. While we continued to work in the domain code which used the interfaces, a junior dev was tasked with creating better implementations. Those implementations were later swapped in, all was well.
As I mentioned earlier, this can all be accomplished without an IoC container framework. It's the pattern itself that's important, really.
First of all what is IOC? It means that responsibility of creating the dependent object is taken away from the main object and delegated to third party framework. I always use spring as my IOC framework and it bring tons of benefit to the table.
Promotes coding to interface and decoupling - The key benefit is that IOC promotes and makes decoupling very easy. You can always inject an interface in your main object and then use the interface methods to perform tasks. The main object does not need to know which dependent object is assigned to the interface. When you want to use a different class as dependency all you need is to swap the old class with a new one in the config file without a single line of code change. Now you can argue that this can be done in the code using various interface design patterns. But IOC framework makes its walk in a park. So even as a newbie you become expert in levering various interface design patterns like bridge, factory etc.
Clean code - As most of object creation and object life-cycle operations are delegated to IOC container you saved from the writing broiler point repetitive code. So you have a cleaner, smaller and more understandable code.
Unit testing - IOC makes unit testing easy. Since you are left with decoupled code you can easily test the decoupled code in isolation. Also you can easily inject dependencies in your test cases and see how different component interacts.
Property Configurators - Almost all the applications have some properties file where they store application specific static properties. Now to access those properties developers need to write wrappers which will read and parse the properties file and store the properties in format that application can access. Now all the IOC frameworks provide a way of injecting static properties/values in specific class. So this again becomes walk in the park.
These are some of the points I can think right away I am sure there are more.