Should I make Enterprise Library Data Block Database object static? - enterprise-library

Can anyone clarify if Enterprise Library's Database object can be made static without any thread-safety issues?

Yes, an Database instance is thread-safe. It is just a big factory spitting out new objects like connections. The instance itself doesn't change state after it is created. When you look at the source code you can see this clearly. The objects it produces are of course not thread-safe.

You can, but there's no significant reason to. Database instances are cheap to create and don't hold any state.

No don't do it. I tried it and was sorry that I did. While it was thread safe it slowed down my query requests from a web app dramatically. I thought I was being smart skirting the creation of metadata but it gummed things up instead. Now I provide a brand new instance every request and it's as happy and as fast as can be.

Related

are there good caching patterns on iOs?

I'm about to implement caching on my app, I imagine there are already good patterns on how to do that.
I think I'm going to use Core Data but I was wondering the best way to do that.
Most of the doc I found are just for Core Data tutorial.
What I do is to generate the NSManagedObject but then I also use a similar class with my additional methods, this to be decoupled from future fields addition keeping the generated one independent.
Is there some tutorial on the best way to handle object caching with Core Data?
Thanks in advance.
For keeping the hand-written code separate from the machine-generated code when using Core Data, have a look at mogenerator. Very useful.
As far as caching goes, Core Data's pretty decent, and with judicious use of batch faulting and pre-fetching, you can fairly easily manage the number of trips to the persistent store. The faulting mechanism works well in my experience, so be wary of premature optimisation when it comes to Core Data.
The advice Apple gives here is good, in particular use the profiling tools to see the part of your app that isn't working efficiently, and then address that specifically, rather than spending time writing code for a problem that doesn't exist.
Caching to file system is discouraged on iOS. Use Core Data for permanent storage, not temporary caching when possible.
There are however two in memory caching facilities provided by Apple.
NSURLCache for caching responses using the URL loading system (NSURLConnection and friends.). Simply create a new instance, and set it using +[NSURLCache setSharedURLCache:].
NSCache for caching any object. Just create an instance, add and fetch cached object using keys like form a normal dictionary collection. Supports both count and cost limits, as well as locking cached objects using the NSDiscardableContent protocol.
You could also use a in-memory NSPersistentStore for Core Data if you like to work with managed objects, that are only to live for one execution of the app.

How to create a persistant iphone cache

So I have been doing lots of reading and found out NSCache is not persistent which is a slight problem for what I need to do. I have heard that I will need to use Core data instead... but I don't have any experience with core data so am wondering if its the only solution for persistent data.
The app will allow the user to search through a catalog, by typing in a search parameter in the code and select a distributor for their search parameter. What I want to do when the app loads is download the list of distributors and save them to a "cache" the will be persistent (till when the header I will make at some point changes and demands the app to update the cache), so that if the user turns the app of or the phone next time then open it the manufacture.
Now that I'm getting abit deeper into my app I'm getting abit lost in things for instance how would setting up a cache work with regards to NSURLConnection.
Any suggestions or code examples would be greatly appreciated..
This previous answer of mine might help you decide.
To sum it up:
If your data is small, static and low-complexity, use a collection class and write it to disk using the built-in class methods
If the data is static, low-complexity but large, SQL may be a good solution especially if you already know it.
If the data is dynamic and complex regardless of size, then Core Data is your best choice.
Viewed purely from the technical perspective, Core Data is always the best choice for iOS/MacOS API apps. Core Data is not just a persistence API, it is an API for creating the model layer of the Model-View-Controller design paradigm that the Apple API uses. It not only persist the data, but models it, validates its and provides an easy interface to the rest of the API.
If your going to be writing iOS apps, you need to eventually learn Core Data. However, it does have a learning curve and you should pick the method right now that will let you ship a usable app.
You can also check out sqlite. Here's another question that discusses getting started with sqlite on the phone: Where's the best SQLite 3 tutorial for iPhone-SDK?
The advantage to sqlite is that it is fairly easy to pick up. The downside is that you have to write queries for everything, and that can be a pain. It doesn't save objects, just data, numbers or text.

Options for Caching Generic Object Lists for iPhone?

I have an app that connects to an API and retrieves a large number of small objects at a time. These objects are returned from json-framework as a heirarchy of NSDictionary, NSArray, etc. They are basic data types, and the primary structure of most of the api calls is a list of items(which could be hundreds of items long).
I will be displaying the data in a UITableView, but I don't want all the data in memory(as I could potentially eat it all up). I also don't want to hit up the api for the objects again, as they can be cached for a few hours without any problems.
I have thought of a couple of solutions, but I am eager to hear other options. I have thought of using Core Data in various ways, but I'd like to avoid having to create and maintain entities for each type of entity returned from the API. Using Core Data like this seems like overkill. I could use core data to store archived objects, though I worry about the archiving/de-archiving overhead.
I really want a generic store that can keep a list of objects cached, and then be able to retrieve arbitrary items from the list.
The factors that I care about:
Ease of maintenence. If the api changes or we add other objects, I don't want to have a lot of places in the code to change. Storing generic objects(NSCoding compliant) is ideal.
Performance. Caching and retrieval will all be happening while the user is interacting with the app(in the background), but I don't want to consume too many resources to make the app feel slow.
Are there any existing libraries that already exist for this purpose? What options am I missing? Maybe convince me that creating Core Data entities for each data type is actually a good idea for an object cache.
In case you haven't tried out the facebook/Three20 library, they have implemented a disc/memory cache and have used it as one of the fundamental layers inside their network module. I used three20 in my app but I never used this cache layer directly, so I'm not sure about the performance with it. Still, it's a nice thing to keep in mind.
Besides, the Enormego team has implemented a stand-alone photo viewer thing. And inside this photo viewer there is a nicely-working disc-memory cache. I'm not sure whether it has anything to do with the three20 cache. But I do believe it can cache generic objects other than just images. You can try it out by yourself.

Is there any reason why someone would want to create an Core Data model programmatically?

I wonder in which cases it would be good to make an NSManagedObjectModel completely programmatically, with NSEntityDescription instances and all this stuff.
I'm that kind of person who prefers to code programmatically, rejecting Interface Builder. But when it comes to Core Data, I have a hard time figuring out why I should kill my time NOT using the nice Xcode Data Modeler tool.
And since data models are stuck to a given state (except when you want to do some ugly migration operations where thinks probably go wrong and users get mad, really mad), I see no big sense in a data model that's made programmatically for the purpose of changing it all the time.
Did I miss something?
I dont think you missed anything. The only reason I can see to create your model programatically would be if the objects you are modeling are themselves dynamic: you could for instance build a coredata entity (or graph of entities) in response to a web service which changed over time, or was selected by the user. However, I think if you had that or a similar use case, you wouldn't need to write this question (and you'd probably solve it a different way anyway)
So, if your application is dealing with resources that are dynamic, as #Andiih mentioned, then this programatic is the only way to do it. I don't know what my core data entities are until runtime, I don't know what the attributes are, or what the data looks like. So, I ask the server to give me the kinds of resources I should support and what their attributes look like. I build the model, the entities, the properties, the relationships - at runtime. I still want to use Core Data because I'm dealing with a lot of data and I need the benefit of efficient memory management with NSFetchedResultsController, etc. I can only do this programmatically.
The trouble is how to handle migration to try and preserve as much of the persistent store as possible, to reduce the size of the networked data payload after the model changes. Right now I blast the whole model and the persistent store if there's a conflict. I haven't yet figured out a way to create an .xcdatamodel from a programmatically generated model, thus I can't yet create a version mapping to do the migration.
Everything is a trade off. Basically, I think IB and the visual Core Data modeler are the right tool if you're building a simple application. You'll need to make the determination when your application becomes large/complex enough that you prefer to have direct control over all aspects of the code.
Regarding Interface Builder, if you have an application with a variety of complex interactions between view controllers, and multiple custom controls, I find code more appropriate.
For Core Data, the question is pretty much the same. Does your project have a defined scope? Can you foresee everything in that scope being done within the visual modeler? If so, it's probably fine. For other projects, where you may be asked to add features on an ongoing basis, perhaps it's better to spend a little more time writing it out so you have more flexibility later.
One other thing to consider, that doesn't get mentioned much, is it's MUCH harder to ask for help with IB or any hybrid visual design/code system. When something does go wrong, or you need help, it's way easier to post your code, than try to explain what's going on in a visual modeler.
In general, there's no reason to build the managed object model in code. There's nothing you can do in code that can't be done in the model editor. There are some fancy tricks you can do in code, however, to work with multiple models. For example, you can merge two models, establishing cross-model relationships between entities in those models at load time (see Cross-model relationships in NSManagedObjectModel from merged models?).
Regarding whether it's a good idea to code or use the graphical editor, I think the balance tips heavily towards the graphical editor in this case. Being able to verify the model by visual inspection instead of (rather convoluted) code is a win. The model can still be verified by unit test, if you desire.
I have one use case that might be valid, what if you load some data from the internet whether it is XML from an RSS Feed or WSDL response, then flatten those responses into a tabular from generating an in memory data table and finally mash it all up into a single coherent data model, then you can create the entities for those in memory data tables and create master/detail relationships. That's one case I think Core Data data model generated programmatically could become handy and a powerful feature.
I've changed models programmatically in unit tests. For example, I wrote a class that is designed to work with Core Data models that have a particular protocol attached. Instead of testing against a random implementation, I mutated the default model by adding one just in the unit tests programmatically, and tested against that test-only model.

ORM on iPhone. More simple than CoreData

The question is rather simple. I know that there is SQLite. There is Core Data also. But I need something in between. More object-oriented than SQLite API and simplier than Core Data.
Main points are:
I need access to stored entities only by id. No queries required.
I need to store items of a single type, it means that I can use only one table if I choose SQLite.
I want automatic object-relational conversion. Or object-storage if the storage is not relational.
I can use object archiving, but I have to implement things (NSArchiver).
But I want to write some kind of class and get persistence automatically. As it can be done with Hibernate/ActiveRecord/Core Data/etc.
Thanks.
Everything you've said you want here is completely compatible with Core Data. Apple's giving you a solution that meets your stated needs exactly, so why are you trying to avoid it?
Beyond BNRPersistence, which Alex points out, I don't think you're going to find anything that maintains object relationships, yet is simpler than Core Data on the Cocoa platforms. An object wrapper around SQLite like FMDB still requires you to manage relationships in your own code.
Maintaining relationships between objects is a non-trivial task, which is why you see so few of these frameworks out there. Core Data gets it right for many people, so there isn't that much motivation among developers to build an alternative to Apple's solution. BNRPersistence was created out of Aaron Hillegass' long-time frustration with certain aspects of Core Data, but many people (like me) are perfectly happy with the way Core Data does what it does.
You might also want to look at Core Resource, a newer framework that provides some wrappers around Core Data to make common tasks easier.
You might consider a non-Objective-C approach to serializing objects, just as XML or JSON, where you don't have to write serialization code, if you don't want to, because the framework does it for you. For example, put your objects into a key-value attribute pairing with NSDictionary (via a wrapper class or whatever) that points to another record's id key, and then encode the mess with json-framework's JSONRepresentation call. You'd probably need to do your own relationship integrity tests, but voila, instant relational database.
Take a look at BNRPersistence.