Passing Data Between .Swift Files in Xcode [closed] - ios

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
i'm new to swift, i have a project in Xcode 7 Beta, and i have extension files and etc. i have 3 .swift files (not for view controllers) in my project, and i want to define a variable or constant in one of them and access that , all over the project. for example define a var in First.swift , and access to that in Second or Third.swift files. i know about NSUserDefaults in Xcode, but i don't want to use that.
Also i know that how i can pass data between viewcontrollers (using prepareforsegue and etc.)
but i want to pass data between .swift files.

One way to do it is you can encapsulate them in struct and can access anywhere.
You can define static variables or constant in swift also.Encapsulate in struct
struct MyVariables {
static var yourVariable = "someString"
}
You can use this variable in any class or anywhere:
let string = MyVariables.yourVariable
println("Global variable:\(string)")
//Changing value of it
MyVariables.yourVariable = "anotherString"
Or you can declare global variables which you can access anywhere.
Reference from HERE.

Take a look at http://www.raywenderlich.com/86477/introducing-ios-design-patterns-in-swift-part-1
The idea is to create one instance of a class and access it anywhere in your files/classes.
If you just need to share constants, the Dharmesh's solution is simpler.

You can create custom subclass of NSObject class. Declare all variables there. Create single instance of object of that class and access variables through the object of that class in any view controller.
class Singleton {
class var sharedInstance: Singleton {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: Singleton? = nil
static var yourVariable = "someString"
}
dispatch_once(&Static.onceToken) {
Static.instance = Singleton()
}
return Static.instance!
}
}
then in any viewController, you can access the variables.

Related

Swift - Prevent creating two reference of class [duplicate]

This question already has answers here:
Understanding Singleton in Swift
(2 answers)
Closed 3 years ago.
I have app delegate which is a single point in app. Also I've created ApplicationManager class which is a part of app delegate now.
so what I want to achieve is to protect my code from other developers to be used in a wrong way.
So let's say my ApplicationManager looks like this:
class ApplicationManager {
var api: API?
static func instance() -> ApplicationManager {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
fatalError()
}
return appDelegate.applicationManager
}
}
I want to make sure that used will use ApplicationManager via:
let am = ApplicationManager.instance() but not like this am = ApplicationManager() which will create one more manager which I don't want.
is there a way to show build time error? or drop some message? or crash in crash in case there are more that one ApplicationManager in app =)
Simply make your init private:
private init() {}
Also, the singleton pattern would be usually implemented simply as:
static let shared = ApplicationManager()
Called as ApplicationManager.shared. If you want AppDelegate to create the instance, private init won't work.

Best Approach to Refresh a Class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Simply i want to know what is the Best Approach to refresh a class.Like when same class is used from diff-diff section of application where we pass some data to that class ,I can do it by simply taking a global variable and change it's value from other class's But i want to know some another approach which is best suitable for this kind of Things.
The best way to handle this kind of structure, where the class needs to be effectively shared between other MVCs, is to make the class a singleton. This means that only one instance of a class is ever used. That way if one MVC changes the class you don't need to sync the change because every MVC uses the same instance.
To make a class a singleton you do the following
Create a static var which is an instance of the class
Make the init function private so no other class can initialise it
Eg
class Singleton {
static var shared = Singleton()
var info = "singleton info variable"
private init() {}
func doSomething() {}
}
To access the class you do the following
Singleton.shared.doSomething()
or
let singletonInfo = Singleton.shared.info
You have two options:
(Simplified) - Either you create a new instance and pass it on:
class MyClass {
let name: String
init(name: String) { self.name = name }
}
class MyViewController: UIViewController {
let myClass = MyClass(name: "Hello World")
func actionThatCausesSegue() {
let copyOfMyClass = MyClass(name: self.myClass.name)
self.performSegueWithIdentifier(identifier: "MySegue", sender: copyOfMyClass)
}
}
Or you can use structs:
struct MyStruct {
let name: String
init(name: String) { self.name = name }
}
class MyViewController: UIViewController {
let myStruct = MyStruct(name: "Hello World")
func actionThatCausesSegue() {
// structs are always copied when passed around.
self.performSegueWithIdentifier(identifier: "MySegue", sender: self.myStruct)
}
}
Structs are always copied, when you pass them around. Here's the explanation from the Swift Programming Language Guide by Apple:
Structures and Enumerations Are Value Types
A value type is a type whose value is copied when it is assigned to a
variable or constant, or when it is passed to a function.
You’ve actually been using value types extensively throughout the
previous chapters. In fact, all of the basic types in Swift—integers,
floating-point numbers, Booleans, strings, arrays and dictionaries—are
value types, and are implemented as structures behind the scenes.
All structures and enumerations are value types in Swift.
You can read more about the differences here.
It depends on the situation, but I sometimes do this for views in iOS. For example when the data model changes you want the view to update, so I implement a method in the controller called configureThingyViewWithThingy which takes the new 'thingy' and updates the view. Then whatever mechanism you're using to monitor data model changes (KVO, notifications, etc.) will call this method to reconfigure the view with the new data.

When do I want to use static, final, private in swift 2.2? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I kind of know when to use those different keywords, but can someone clarify for me when exactly do I want to use them, and how do they affect my apps during runtime?
static
You use a static method or property when you need some data without allocating new object, the most common use of static could be the singleton design pattern or when you have some helper class.
So for example in a function you can call:
let temp = Helper.staticMethod();
where
class Helper {
private let test1234 = false
private func privateMethod() {
}
private static func privateStaticMethod() -> Int {
return 0
}
static func staticMethod() -> Int {
self.privateMethod() // Error
self.test1234 // Error
self.test1234 // Error
Helper.privateStaticMethod() // OK
return 0
}
}
from staticMethod you can't have the access to NOT static method or property of the class Helper
final
It should be best practice declare all classes final and remove it just if you have to subclass them. Final provides you a compile time error if you try to subclass a final class and so this can help you to have a clean architecture without risking to create messy code and it help the readability of the code as well.
final class FinalClass {
}
class Sub1: FinalClass {
} //Error
class Base {
}
class SubBase: Base {
} //OK
private
A private class / property is not visible outside the scope.
It helps you to have a good encapsulation in your architecture.
class A {
private let test = 1
let test2 = 1
}
let classA = A()
classA.test //Error
classA.test2 //OK
I suggest reading the Swift documentation for better explanations:
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Inheritance.html
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AccessControl.html
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Methods.html

Ios swift class without instantiate

How do you (if possible) create a class that anything that references it gets the same object?
So, if I had a LoginClass
and I dont want to create a new instance in each file but rather be able to just do
LoginClass.userID
in any file without first creating an instance of it?
It possible. Use singleton:
Stackoverflow question
Tutorial by Ray Wenderlich
You are looking for a Singleton
This is the code
class Login {
static let sharedInstance = Login()
var userID: String?
private init() {}
}
This is how you retrieve the same instance
Login.sharedInstance
And this is how you use it
Login.sharedInstance.userID = "123"
In a different point of your code...
print(Login.sharedInstance.userID) // 123
Creating one instance per application life cycle means you want to implement Singleton pattern. You can implement singleton like this
class LoginManager {
static let sharedInstance = LoginManager()
var userId:String?
var name:String?
}
And now you can use this like
LoginManager.sharedInstance.userId

Declare public static variable in objective c [duplicate]

This question already has answers here:
Objective-C: how to declare a static member that is visible to subclasses?
(3 answers)
Closed 8 years ago.
I want a static varibale in .h of a class and want it to be inherited to its child class.
#interface :UIViewController
static bool isSearchWindowOpen ; //something like this.
#end
If i write like :
static bool isSearchWindowOpen ;
#interface :UIViewController
#end
it works fine but cannot be inherited by child classes.
pls suggest.
This sounds a bit like you are confusing this with some other programming language, like C++. In Objective-C, just like C, a static variable is a variable with file scope. If you declare a static variable in a header file, then any source file including that header file has its own copy of the static variable.
You'd probably want a class method
+ (BOOL)isSearchWindowOpen
with implementation
static BOOL sSearchWindowOpen;
+ (void)setSearchWindowOpen:(BOOL)open { sSearchWindowOpen = open; }
+ (BOOL)isSearchWindowOpen { return sSearchWindowOpen; }
Probably even better to write code that checks whether the search window is open, instead of relying on a static variable that you have to track correctly all the time.
The variable as declared has nothing to do with the class. It’s a global static in the “C sense”: only code in the same file can access it. (See Wikipedia for details.) You can write class accessors:
static BOOL foo;
+ (void) setFoo: (BOOL) newFoo
{
foo = newFoo;
}
That way the class descendants can access the variable, too. But it’s not a good idea anyway. What problem are you trying to solve?

Resources