My application uses two separate Realm instances (the second comes from a library).
The application itself uses Realm.Configuration.defaultConfuguration and the library creates its own configuration (Realm.Configuration(...)).
On runtime (after inspecting with Realm Browser), we see that both instances (each live in its own file) contain the models from both Realms. This, of course, has implications on migrations.
I know that when both use the same configuration we should set configuration.objectTypes, but I didn't expect it to matter when each instance has its own configuration.
How can two distinct configs share any data between them? It seems like a bug in Realm - or maybe I'm missing something.
An explanation was posted in Realm's issues on GitHub. I'm copying the response here for future searches:
By default objectTypes will include all RealmSwift.Object
subclasses, regardless of where they are defined.
A library which uses Realm should override
shouldIncludeInDefaultSchema() to exclude its types from the default
objectTypes (i.e. add public override class func
shouldIncludeInDefaultSchema() -> Bool { return false } to the class
definitions) and then explicitly list the types it uses. This lets any
applications using the library continue to simply use the automatic
class discovery.
The credit goes to Thomas Goyne (Realm developer).
Related
Thanks in advance for any help.
I have a caching service I've implemented with a core data stack in Swift 3.1. The exposed interface conforms to this protocol:
protocol WeekForecastCacheService {
func add(cacheModels: [DayForecastCacheModel])
func get(cityId: Int, callback: #escaping ([DayForecastCacheModel]?) -> () )
}
Ideally I want the internals of my core data stack to stay private.
However I also want to be able to unit test the class. Specifically the exposed interface. Because the core data stack is persistent I want to be able to delete every entity (a reset if you will to start tests in a known state). How do I go about doing this while keeping the unit test implementation outside of my main target.
Ideally I would also like my tests to be independent of implementation...
I'm thinking along the lines of the following but could do with some advice:
Add a delete all function to the cache class
Use a class extension and implement the functionality there - it would mean a fair amount of copy paste
Change private functions / variables to be internal giving enough access to easily create a delete all function in a class extension
Stop worrying because only protocols are used by classes consuming the service so it doesn't matter if functions and properties within the class are not private
When unit testing Core Data, a typical approach is to use the in-memory store type to effectively remove the "persistent" part of Core Data. With an in-memory store you get all of Core Data's usual capabilities, but the persistent store isn't written to a file so it always starts off empty. That gets you to a known starting state. If necessary you can pre-load some other known state into the in-memory store before beginning the test.
The key for this is NSInMemoryStoreType. If you're setting explicitly adding the persistent store, that would be the type value when calling addPersistentStore(ofType:configurationName:at:options:). If you're using NSPersistentContainer, you'd include the store type in the persistentStoreDescriptions property.
I was trying to implement a grails SearchService that indexes certain text and stores it in memory for faster lookup. In order to store this data, I was trying to use a private static property in the Service to store the data, but the property was randomly resetting values. After rereading documentation, I realized that this is likely because grails services are supposed to be stateless since the employee the singleton pattern. Still, not sure I understand how a static variable can vary. Does the JVM load separate copies of service classes per thread? Not sure I'm wrapping my head around what's happening.
Nonetheless, now that I know I can't rely on static variables to store application-wide data, what's the best approach to store and access data for use across the application, while keeping synchronization and avoiding races?
Caused by: java.lang.IllegalStateException: Method on class [TEXTSTORE] was used outside of a Grails application. If running in the context of a test using the mocking API or bootstrap Grails correctly.
at SearchService.buildIndex(SearchService.groovy:63)
at SearchService$_indexAllDomains_closure2.doCall(SearchService.groovy:42)
at SearchService.indexAllDomains(SearchService.groovy:41)
at SearchService.$tt__rebuildIndex(SearchService.groovy:48)
at SearchService.afterPropertiesSet(SearchService.groovy:35)
... 4 more
You seem to be a bit confused about services in Grails. There is no reason why a service (defaulting to singleton) can't have shared state. It's not uncommon for a service to populate some cached or indexed data when it is created so it can be used by multiple callers.
Most often this is done by implementing the org.springframework.beans.factory.InitializingBean interface and making use of the afterPropertiesSet() method which is called when the service (Spring bean) has been created in the application context and all dependencies have been resolved.
For example:
package com.example
import org.springframework.beans.factory.InitializingBean
class MyExampleService implements InitializingBean {
private List data
def otherService
void afterPropertiesSet() {
data = otherService.doSomethingToFetchData()
}
// .. other stuff
}
By hooking into the lifecycle of the bean you can be fairly sure that even in development (when your service reloads because you've changed some code) it will still have the data needed.
I am developing an iOS application in Swift 2.
I am struggling with when to create new classes to handle discrete pieces of functionality.
For example, I have followed this to bring in environment dependent variables: http://appfoundry.be/blog/2014/07/04/Xcode-Env-Configuration/
I can get those variables using:
let path = NSBundle.mainBundle().pathForResource("Configuration", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path!)
url = dict!.objectForKey("envURL") as String
But should I do that code once, in a singleton sharedInstance, or should I just write it when required?
Within my Configuration.plist I have a number of different key/value pairs. I need to access the values within multiple ViewControllers, which means I could be writing those three lines in 5 different places. I could write them once for each key/value pair and save the result to a property of a Singleton. That would save lines, but is that the right way of doing it?
Another example is I make the same REST call a few times in different view controllers. Should I write a new class to handle that call and then use that instead?
I think this is due to lack of Object Oriented programming experience, so any pointers would be really helpful.
Thanks
The singleton pattern should not be your first tool for sharing behavior between classes. Singletons have their place but I find them to be heavily overused in iOS applications. Use a singleton when you absolutely must enforce that there is one and only one instance of a class. Avoid using singletons as globals (calling +shared___) when you just want several objects to have access to some shared state or behavior.
In this case you have some configuration loading behavior which you do not want to repeat. That's a good instinct. We might start by extracting that behavior into a struct whose responsibility is to provide an interface to your app configuration settings:
struct Configuration {
static func get(key: String) -> String {
let path = NSBundle.mainBundle().pathForResource("Configuration", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path!)
return dict!.objectForKey(key) as! String
}
}
Now your controllers can each load different keys by calling a static method:
Configuration.get("envURL")
If you determine that you need to cache these configuration values you might switch this struct become a class with an instance method and maintain a cache on a Configuration instance. Each controller could then create it's own instance of Configuration. If you need to share a common Configuration you might create one and pass it to each of your view controllers when you create them.
Similarly for your REST network calls. You could create a class or struct which provides an interface for interacting with this API. Your controllers can then create and work with instances of this class on demand, or be passed an instance if it is necessary for them to share some state.
This isn't directly related to that specific example, but if you're having issues reusing code, you may want to look into Swift Extensions. They are a great way to extend the functionality of an existing class or protocol.
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Extensions.html
For instance, if you were using a 3rd party library for your restful APIs you could use an extension on the manager to define methods that take the specific params needed for the various endpoints.
But should I do that code once, in a singleton sharedInstance, or should I just write it when required?
if you find you are reusing that same piece of code many times in the same class pull it out into a separate, private "helper" method. if you are using it across several classes, You can write a utility class or classes which contain common utilities. Many people call this kind of class / package a "commons"
Another example is I make the same REST call a few times in different view controllers. Should I write a new class to handle that call and then use that instead?
when dealing with REST interfaces I like to make client classes to interact with them. Write one class that makes all the different calls you want to make to a particular REST API. Each call could be represented by a different method which takes all the arguments and parameters you want to pass to the API. That method should then deserialize and return the value it received from the API.
It's possible to add extensions to existing Swift object types using extensions, as described in the language specification.
As a result, it's possible to create extensions such as:
extension String {
var utf8data:NSData {
return self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
}
}
However, what's the best naming practice for Swift source files containing such extensions?
In the past, the convention was to use extendedtype+categoryname.m for the Objective-C
type as discussed in the Objective-C guide. But the Swift example doesn't have a category name, and calling it String.swift doesn't seem appropriate.
So the question is: given the above String extension, what should the swift source file be called?
Most examples I have seen mimic the Objective-C approach. The example extension above would be:
String+UTF8Data.swift
The advantages are that the naming convention makes it easy to understand that it is an extension, and which Class is being extended.
The problem with using Extensions.swift or even StringExtensions.swift is that it's not possible to infer the purpose of the file by its name without looking at its contents.
Using xxxable.swift approach as used by Java works okay for protocols or extensions that only define methods. But again, the example above defines an attribute so that UTF8Dataable.swift doesn't make much grammatical sense.
I prefer having a + to underline the fact it contains extensions :
String+Extensions.swift
And if the file gets too big, you can then split it for each purpose :
String+UTF8Data.swift
String+Encrypt.swift
There is no Swift convention. Keep it simple:
StringExtensions.swift
I create one file for each class I'm extending. If you use a single file for all extensions, it will quickly become a jungle.
I prefer StringExtensions.swift until I added too much things to split the file into something like String+utf8Data.swift and String+Encrypt.swift.
One more thing, to combine similar files into one will make your building more faster. Refer to Optimizing-Swift-Build-Times
Rather than adding my comments all over the place, I'm surfacing them all here in one answer.
Personally, I take a hybrid approach that gives both good usability and clarity, while also not cluttering up the API surface area for the object that I'm extending.
For instance, anything that makes sense to be available to any string would go in StringExtensions.swift such as trimRight() and removeBlankLines().
However, if I had an extension function such as formatAsAccountNumber() it would not go in that file because 'Account Number' is not something that would naturally apply to any/all strings and only makes sense in the context of accounts. In that case, I would create a file called Strings+AccountFormatting.swift or maybe even Strings+CustomFormatting.swift with a formatAsAccountNumber() function if there are several types/ways to actually format it.
Actually, in that last example, I actively dissuade my team from using extensions like that in the first place, and would instead encourage something like AccountNumberFormatter.format(String) instead as that doesn't touch the String API surface area at all, as it shouldn't. The exception would be if you defined that extension in the same file where it's used, but then it wouldn't have it's own filename anyway.
If you have a team-agreed set of common and miscellaneous enhancements, lumping them together as an Extensions.swift works as Keep-It-Simple first level solution. However, as your complexity grows, or the extensions become more involved, a hierarchy is needed to encapsulate the complexity. In such circumstances I recommend the following practice with an example.
I had a class which talks to my back-end, called Server. It started to grow bigger to cover two different target apps. Some people like a large file but just logically split up with extensions. My preference is to keep each file relatively short so I chose the following solution. Server originally conformed to CloudAdapterProtocol and implemented all its methods. What I did was to turn the protocol into a hierarchy, by making it refer to subordinate protocols:
protocol CloudAdapterProtocol: ReggyCloudProtocol, ProReggyCloudProtocol {
var server: CloudServer {
get set
}
func getServerApiVersion(handler: #escaping (String?, Error?) -> Swift.Void)
}
In Server.swift I have
import Foundation
import UIKit
import Alamofire
import AlamofireImage
class Server: CloudAdapterProtocol {
.
.
func getServerApiVersion(handler: #escaping (String?, Error?) -> Swift.Void) {
.
.
}
Server.swift then just implements the core server API for setting the server and getting the API version. The real work is split into two files:
Server_ReggyCloudProtocol.swift
Server_ProReggyCloudProtocol.swift
These implement the respective protocols.
It means you need to have import declarations in the other files (for Alamofire in this example) but its a clean solution in terms of segregating interfaces in my view.
I think this approach works equally well with externally specified classes as well as your own.
Why is this even a debate? Should I put all my sub classes into a file called _Subclasses.swift. I think not. Swift has module based name spacing. To extend a well known Swift class needs a file that is specific to its purpose. I could have a large team that creates a file that is UIViewExtensions.swift that express no purpose and will confuse developers and could be easily duplicated in the project which would not build. The Objective-C naming convention works fine and until Swift has real name spacing, it is the best way to go.
I have an C# dll project for which I have to store the runtime settings in an external XML file, and this dll will be used in an ASP.NET/ASP.NET MVC application for which I also have to store the runtime settings in a external file.
Which IoC container can be used to create an object with the runtime settings loaded from a specific external file (or app.config/web.config), and also works for web applications running in medium trust? Any howto/tutorial would be greatly appreciated.
So far I've found only this articles:
Use Castle Windsor to Read Your Config Files Automatically
Getting rid of strings (3): take your app settings to the next level
Update
I'm sending mails from my dll to a variable number of SMTP servers, based on the current record type. For type A I'm using a given SMTP server+port, for type B I'm using an alternate set of server+port values. Of course, I want to be able to modify those values after deployment, so I store them in a XML file.
If I'm storing the SMTP settings as a SMTPConfiguration class with 2 properties (SMTPServer as String and SMTPPort as Int32), is it possible to return from an IoC container the required object based on the given record type, and what is the best way to read the runtime settings in order to build the returning object?
Update2
Let's say I'm storing in the configuration file the following parameters: ASMTPServer, BSMTPServer, ASMTPPort, BSMTPPort.
I can use Castle DictionaryAdapter to read all those settings as properties of an AppConfiguration class.
What is the recommended method to specify that the required SMTPConfiguration class should use ASMTPServer and ASMTPPort values if I'm using a type A record as a parameter (and should use BSMTPServer and BSMTPPort values if I'm using a type B record as a parameter) ? Also, how can I specify that the AppConfiguration is required in this process?
Is there a pattern for initializing objects created wth a DI container
Windsor Config Parameters With Non-Primitive Types