Well, here's another 'Missing argument for parameter #1 in call' issue. (Seems Apple could do a better job naming its errors :-p )
In my class, I'm calling a private function libraryVisibility(), and on that line I get a Missing argument for parameter #1 in call error on compilation. Don't really understand why.
Anyhow, here's the code:
import Cocoa
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var libraryState: Bool = libraryVisibility()
func applicationDidFinishLaunching(aNotification: NSNotification) {
…
}
private func libraryVisibility() -> Bool {
…
// dostuff and return boolean
return true
}
}
You can't call instance functions in the default initialiser of a property
You can either make your libraryVisibility() function a class function:
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var libraryState : Bool = AppDelegate.libraryVisibility()
private class func libraryVisibility() -> Bool {
let homeUrl = NSURL(string: NSHomeDirectory())
let libraryUrl = NSURL(string: "Library", relativeToURL: homeUrl)
return libraryUrl!.hidden
}
}
Or you could make your libraryState property a lazy property:
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
lazy var libraryState : Bool = self.libraryVisibility()
private func libraryVisibility() -> Bool {
let homeUrl = NSURL(string: NSHomeDirectory())
let libraryUrl = NSURL(string: "Library", relativeToURL: homeUrl)
return libraryUrl!.hidden
}
}
The property will then get initialised the first time you use it.
Mike Buss has a nice usage guide on how to use lazy variables.
Ok, I have solved it, but not entirely sure why this is working:
Giving the libraryState variable a default value and setting it inside applicationDidFinishLaunching seems to do the trick:
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var libraryState: Bool = false
func applicationDidFinishLaunching(aNotification: NSNotification) {
libraryState = libraryVisibility()
}
}
Related
I am trying to implement undo/redo in my model. So I made my model class a subclass of NSResponder, and then implemented the following:
note: this code is edited based on more research after comments
func setAnnotations(_ newAnnotations: [Annotation]) {
let currentAnnotations = self.annotations
self.undoManager.registerUndo(withTarget: self, handler: { (selfTarget) in
selfTarget.setAnnotations(currentAnnotations)
})
self.annotations = newAnnotations
}
Annotation is a struct.
The code inside the closure never gets executed. Initially I noticed that undoManager is nil, but then I found this snippet:
private let _undoManager = UndoManager()
override var undoManager: UndoManager {
return _undoManager
}
Now undoManager is no longer nil, but the code inside the closure still doesn't get executed.
What am I missing here?
I can't reproduce any issue now that you've made your undo register code make sense. Here is the entire code of a test app (I don't know what an Annotation is so I just used String):
import Cocoa
class MyResponder : NSResponder {
private let _undoManager = UndoManager()
override var undoManager: UndoManager {
return _undoManager
}
typealias Annotation = String
var annotations = ["hello"]
func setAnnotations(_ newAnnotations: [Annotation]) {
let currentAnnotations = self.annotations
self.undoManager.registerUndo(withTarget: self, handler: { (selfTarget) in
selfTarget.setAnnotations(currentAnnotations)
})
self.annotations = newAnnotations
}
}
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
let myResponder = MyResponder()
#IBOutlet weak var window: NSWindow!
func applicationDidFinishLaunching(_ aNotification: Notification) {
print(self.myResponder.annotations)
self.myResponder.setAnnotations(["howdy"])
print(self.myResponder.annotations)
self.myResponder.undoManager.undo()
print(self.myResponder.annotations)
}
}
The output is:
["hello"]
["howdy"]
["hello"]
So Undo is working perfectly. If that's not happening for you, perhaps you are mismanaging your "model class" in some way.
By the way, a more correct to write your registration closure is this:
self.undoManager.registerUndo(withTarget: self, handler: {
[currentAnnotations = self.annotations] (selfTarget) in
selfTarget.setAnnotations(currentAnnotations)
})
This ensures that self.annotations is not captured prematurely.
I have the following code in Playground -I'm learning delegation-...
import UIKit
protocol FollowThisProtocol {
func passingTheValue(aValue: String)
}
class IPassTheValues{
var aDelegate: FollowThisProtocol!
func runThisFunc(){
aDelegate.passingTheValue(aValue: "I like this game")
}
}
class IReceiveTheValues: FollowThisProtocol{
var localString: String!
var instanceOfClass: IPassTheValues!
func runReceivefunc(){
instanceOfClass.aDelegate = self
}
func passingTheValue(aValue: String) {
localString = aValue
}
}
When I attempt to
print(IReceiveTheValues().localString)
it's giving me nil
It also gives me nil if I run the following lines before attempting to print(IReceiveTheValues().localString)...
IPassTheValues()
IReceiveTheValues()
could you please help me understand why the value is not being passed from the 1st class to the 2nd..?
Or if you can spot something in my code that is contradicting itself, could you please point it out..?
Appreciate your time and help.
You need to create the IPassTheValues object before assigning yourself as the delegate, and then call runThisFunc() on the instance:
func runReceivefunc(){
instanceOfClass = IPassTheValues()
instanceOfClass.aDelegate = self
instanceOfClass.runThisFunc()
}
Then test:
// Create the `IReceiveTheValues` object
let irtv = IReceiveTheValues()
// Run the method
irtv.runReceivefunc()
// Get the resulting string
print(irtv.localString)
I suggest 2 other changes. Make your delegate weak so that you don't get a retain cycle which makes it impossible to delete either object. In order to do that, you will need to add : class to your protocol declaration because only reference objects (instances of a class) can be weak.
Here's the modified code. Try it and see what happens when you delete weak.
protocol FollowThisProtocol: class {
func passingTheValue(aValue: String)
}
class IPassTheValues{
weak var aDelegate: FollowThisProtocol!
func runThisFunc(){
print("Calling delegate...")
aDelegate.passingTheValue(aValue: "I like this game")
}
deinit {
print("IPassTheValues deinitialized")
}
}
class IReceiveTheValues: FollowThisProtocol{
var localString: String!
var instanceOfClass: IPassTheValues!
func runReceivefunc(){
instanceOfClass = IPassTheValues()
instanceOfClass.aDelegate = self
instanceOfClass.runThisFunc()
}
func passingTheValue(aValue: String) {
print("Receiving value from helper object...")
localString = aValue
}
deinit {
print("IReceiveTheValues deinitialized")
}
}
func test() {
let irtv = IReceiveTheValues()
irtv.runReceivefunc()
print(irtv.localString)
}
test()
I've been trying to implement a singleton to be used as a cache for photos which I uploaded to my iOS app from the web. I've attached three variants in the code below. I tried to get variant 2 working but it is causing a compiler error which I do not understand and would like to get help on what am I doing wrong. Variant 1 does the caching but I do not like the use of a global variable. Variant 3 does not do the actual caching and I believe it is because I am getting a copy in the assignment to var ic = ...., is that correct?
Any feedback and insight will be greatly appreciated.
Thanks,
Zvi
import UIKit
private var imageCache: [String: UIImage?] = [String : UIImage?]()
class ImageCache {
class var imageCache: [String : UIImage?] {
struct Static {
static var instance: [String : UIImage?]?
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = [String : UIImage?]()
}
return Static.instance!
}
}
class ViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imageView.image = UIImage(data: NSData(contentsOfURL: NSURL(string: "http://images.apple.com/v/iphone-5s/gallery/a/images/download/photo_1.jpg")!)!)
//variant 1 - this code is working
imageCache["photo_1"] = imageView.image
NSLog(imageCache["photo_1"] == nil ? "no good" : "cached")
//variant 2 - causing a compiler error on next line: '#lvalue $T7' is not identical to '(String, UIImage?)'
//ImageCache.imageCache["photo_1"] = imageView.image
//NSLog(ImageCache.imageCache["photo_1"] == nil ? "no good" : "cached")
//variant 3 - not doing the caching
//var ic = ImageCache.imageCache
//ic["photo_1)"] = imageView.image
//NSLog(ImageCache.imageCache["photo_1"] == nil ? "no good" : "cached")
}
}
The standard singleton pattern is:
final class Manager {
static let shared = Manager()
private init() { ... }
func foo() { ... }
}
And you'd use it like so:
Manager.shared.foo()
Credit to appzYourLife for pointing out that one should declare it final to make sure it's not accidentally subclassed as well as the use of the private access modifier for the initializer, to ensure you don't accidentally instantiate another instance. See https://stackoverflow.com/a/38793747/1271826.
So, returning to your image cache question, you would use this singleton pattern:
final class ImageCache {
static let shared = ImageCache()
/// Private image cache.
private var cache = [String: UIImage]()
// Note, this is `private` to avoid subclassing this; singletons shouldn't be subclassed.
private init() { }
/// Subscript operator to retrieve and update cache
subscript(key: String) -> UIImage? {
get {
return cache[key]
}
set (newValue) {
cache[key] = newValue
}
}
}
Then you can:
ImageCache.shared["photo1"] = image
let image2 = ImageCache.shared["photo2"])
Or
let cache = ImageCache.shared
cache["photo1"] = image
let image2 = cache["photo2"]
Having shown a simplistic singleton cache implementation above, we should note that you probably want to (a) make it thread safe by using NSCache; and (b) respond to memory pressure. So, the actual implementation is something like the following in Swift 3:
final class ImageCache: NSCache<AnyObject, UIImage> {
static let shared = ImageCache()
/// Observer for `UIApplicationDidReceiveMemoryWarningNotification`.
private var memoryWarningObserver: NSObjectProtocol!
/// Note, this is `private` to avoid subclassing this; singletons shouldn't be subclassed.
///
/// Add observer to purge cache upon memory pressure.
private override init() {
super.init()
memoryWarningObserver = NotificationCenter.default.addObserver(forName: .UIApplicationDidReceiveMemoryWarning, object: nil, queue: nil) { [weak self] notification in
self?.removeAllObjects()
}
}
/// The singleton will never be deallocated, but as a matter of defensive programming (in case this is
/// later refactored to not be a singleton), let's remove the observer if deallocated.
deinit {
NotificationCenter.default.removeObserver(memoryWarningObserver)
}
/// Subscript operation to retrieve and update
subscript(key: String) -> UIImage? {
get {
return object(forKey: key as AnyObject)
}
set (newValue) {
if let object = newValue {
setObject(object, forKey: key as AnyObject)
} else {
removeObject(forKey: key as AnyObject)
}
}
}
}
And you'd use it as follows:
ImageCache.shared["foo"] = image
And
let image = ImageCache.shared["foo"]
For Swift 2.3 example, see previous revision of this answer.
Swift 3:
class SomeClass
{
static let sharedInstance = SomeClass()
fileprivate override init() {
//This prevents others from using the default '()' initializer
super.init()
}
func sayHello()
{
print("Hello!")
}
}
Invoke some Method:
SomeClass.sharedInstance.sayHello() //--> "Hello"
Invoke some Method by creating a new class instance (fails):
SomeClass().sayHello() //--> 'SomeClass' cannot be constructed it has no accessible initailizers
Swift-5
To create a singleton class:
import UIKit
final class SharedData: NSObject {
static let sharedInstance = SharedData()
private override init() { }
func methodName() { }
}
To access
let sharedClass = SharedClass.sharedInstance
OR
SharedClass.sharedInstance.methodName()
Following are the two different approaches to create your singleton class in swift 2.0
Approach 1) This approach is Objective C implementation over swift.
import UIKit
class SomeManager: NSObject {
class var sharedInstance : SomeManager {
struct managerStruct {
static var onceToken : dispatch_once_t = 0
static var sharedObject : SomeManager? = nil
}
dispatch_once(&managerStruct.onceToken) { () -> Void in
managerStruct.sharedObject = SomeManager()
}
return managerStruct.sharedObject!
}
func someMethod(){
print("Some method call")
}
}
Approach 2) One line Singleton, Don't forget to implement the Private init (restrict usage of only singleton)
import UIKit
class SomeManager: NSObject {
static let sharedInstance = SomeManager()
private override init() {
}
func someMethod(){
print("Some method call")
}
}
Call the Singleton method like :
SomeManager.sharedInstance.someMethod()
I have copied the Parse Swift example for Subclassing:
class Armor : PFObject, PFSubclassing {
override class func load() {
self.registerSubclass()
}
class func parseClassName() -> String! {
return "Armor"
}
}
I get the following errors:
/Parse/Armor.swift:11:1: error: type 'Armor' does not conform to protocol 'PFSubclassing'
class Armor : PFObject, PFSubclassing {
^
__ObjC.PFSubclassing:15:28: note: protocol requires function 'object()' with type '() -> Self!'
#objc(object) class func object() -> Self!
^
__ObjC.PFSubclassing:23:52: note: protocol requires function 'objectWithoutDataWithObjectId' with type '(String!) -> Self!'
#objc(objectWithoutDataWithObjectId:) class func objectWithoutDataWithObjectId(objectId: String!) -> Self!
^
__ObjC.PFSubclassing:30:27: note: protocol requires function 'query()' with type '() -> PFQuery!'
#objc(query) class func query() -> PFQuery!
^
__ObjC.PFSubclassing:35:38: note: protocol requires function 'registerSubclass()' with type '() -> Void'
#objc(registerSubclass) class func registerSubclass()
^
/Parse/Armor.swift:14:9: error: 'Armor.Type' does not have a member named 'registerSubclass'
self.registerSubclass()
^ ~~~~~~~~~~~~~~~~
I saw this answer: https://stackoverflow.com/a/24899411/843151 and tried that solution with no luck, I get the same errors.
Any suggestions of why this is happening? Thanks in advance.
I needed to import the parse PFObject+Subclass.h in my Objective-C bridging header
#import <Parse/PFObject+Subclass.h>
With xCode 6.1.1 I was able to get this working without the bridging header. Just:
import Parse
at the top of the module. For the class declaration I did need to use #NSManaged for the variable types to get them to link to the Parse class variables successfully. Like this:
class PSCategory : PFObject, PFSubclassing {
override class func load() {
self.registerSubclass()
}
class func parseClassName() -> String! {
return "Category"
}
#NSManaged var Name: String
}
Then in my query all the names are dynamically linked:
var query = PSCategory.query() // PFQuery(className: "Category")
query.cachePolicy = kPFCachePolicyCacheElseNetwork // kPFCachePolicyNetworkElseCache
query.maxCacheAge = 60 * 60 * 24 // One day, in seconds.
query.findObjectsInBackgroundWithBlock {
(categories: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
for abstractCategory in categories {
let category = abstractCategory as PSCategory
NSLog("Category Name: %#", category.Name)
}
} else {
NSLog("Unable to retrieve categories from local cache or network")
}
}
Parse recommends initialize() instead of load()
class Armor : PFObject, PFSubclassing {
override class func initialize() {
var onceToken : dispatch_once_t = 0;
dispatch_once(&onceToken) {
self.registerSubclass()
}
}
static func parseClassName() -> String! {
return "Armor"
}
}
It appears that PFSubclassing does not currently work correctly in Swift as is, as of v1.7.2, released April 27, 2015.
I was able to get it working by implementing custom getters and setters for properties as a temporary workaround--which somewhat defeats the purpose, but at least this approach will result in only minor refactoring once PFSubclassing is made ready for Swift.
It is not necessary to add #import <Parse/PFObject+Subclass.h> to the bridging header. But, as indicated in the PFSubclassing Protocol Reference, "Warning: This method must be called before [Parse setApplicationId:clientKey:]," you should register all PFObject custom subclasses before calling Parse.setApplicationId(_:, clientKey:).
Here's an example for a custom PFObject subclass called PFChatLOCMessage:
// In ProjectName-Bridging-Header.h
#import <Parse/Parse.h>
// In AppDelegate.swift
#UIApplicationMain
final class AppDelegate: UIResponder, UIApplicationDelegate {
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
configureParse()
return true
}
func configureParse() {
registerParseSubclasses()
Parse.setApplicationId("...", clientKey: "...")
}
func registerParseSubclasses() {
PFChatLOCMessage.registerSubclass()
}
}
// In PFChatLOCMessage.swift
private let PFChatLOCMessageClassName = "PFChatLOCMessage"
private let userKey = "user"
class PFChatLOCMessage: PFObject {
var user: PFUser! {
get { return self[userKey] as! PFUser }
set { self[userKey] = newValue }
}
override init() {
super.init()
}
override init(user: PFUser) {
super.init()
self.user = user
}
}
extension PFChatLOCMessage: PFSubclassing {
class func parseClassName() -> String {
return PFChatLOCMessageClassName
}
}
I got deadlocks / hangs using override class func initialize - even though that's recommended in the parse documentation.
Thinking about it, it's not a good idea to do threading in the init methods of classes - you never know when or in what context these might get called.
This worked for me - for all my custom subclasses, before I call the parse init methods, I explicitly register them as subclasses.
This way the order in which things get called is well defined. Also, it works for me ;)
MyPFObjectSubclass.registerSubclass()
MyPFObjectSubclass2.registerSubclass()
MyPFObjectSubclass3.registerSubclass()
// etc...
let configuration = ParseClientConfiguration {
$0.applicationId = "fooBar"
$0.server = "http://localhost:1337/parse"
}
Parse.initializeWithConfiguration(configuration)
This is a weird one. I have several classes so far in a test app and everything has been going swimmingly. However, I'm getting the error EpisodePlayerController.Type does not have a member named episodeData when I declare otherThing below.
import UIKit
class EpisodePlayerController: UIViewController {
var episodeData = "Hi"
var otherThing = episodeData
}
Tried restarting Xcode, restarting Mac, recreating the class, renaming the class, etc. At a loss. Might be a bug in my Xcode install, but I'd love to be wrong and not have wait for another release. ;)
This seems to solve the problem:
class EpisodePlayerController: UIViewController {
var episodeData = "Hi"
var otherThing = ""
init(){
otherThing = episodeData
}
}
Take a look at the property reference.
The problem is that as far as Swift is concerned, none of your properties have values until the class is fully initialized. Before that point, you can't interact with 'self' implicitly. (this includes its properties and functions.) I think your class is a good candidate for the #lazy attribute:
import UIKit
class EpisodePlayerController: UIViewController {
var episodeData: String = "Hi"
#lazy var otherData: String = self.episodeData
}
You could also include more complex stuff if you need to:
import UIKit
class ClassTwo {
var episodeData = "Hi"
#lazy var otherData: String = {
// Additional parameters
return self.episodeData
}()
}
This way, you can access self because the property 'otherData' won't be called until 'episodeData' is fully initialized.
Because this view was being called via a segue, I wound up making the variable optional and then calling a function from the segue to set the optional variable and then trigger any function dependent on that variable:
import UIKit
class YourController: UIViewController {
var yourData:NSString?
func setYourData(value:NSString) {
self.yourData = value
dependentFunction()
}
A similar effect can be achieved using the didSet and/or willSet methods:
import UIKit
class YourController: UIViewController {
var yourData:NSString? {
didSet {
// Dependent functionality
}
}
func setYourData(value:NSString) {
self.yourData = value
}
Also, for reference, the segue looks like this:
func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if segue.identifier == "yourSegue" {
var destination:YourController = segue.destinationViewController as YourController
destination.setYourData(someData)
}
}
i think this code will help.
class Square: NamedShape {
var sideLength: Double
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 4
}
func area() -> Double {
return sideLength * sideLength
}
override func simpleDescription() -> String {
return "A square with sides of length \(sideLength)."
}
}
let test = Square(sideLength: 5.2, name: "my test square")
test.area()
test.simpleDescription()”