Unexplainable crash when accessing non-optional property in singleton [closed] - ios

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
My architecture is as follows:
We create a singleton BusinessLogic instance which contains several categories, represented by classes defined in extensions.
class BusinessLogic {
static let shared = BusinessLogic()
private(set) var foo: FooCategory = FooCategory()
}
In a different file we define the category.
extension BusinessLogic {
class FooCategory {
var hasNewItems: Bool = false
}
}
In reality the class is much bigger, but these are the relevant parts.
From my view controllers I access the properties like
BusinessLogic.shared.foo.hasNewItems
This is done throughout the app, and usually works without problems. In this example though, we access the hasNewItems property on viewDidLoad of our UITabBarController, which sometimes leads to crashes. This is unexplainable to me.
Does anyone have an idea what might lead to the crash? We access the BusinessLogic class even on appStart inside the AppDelegate, where everything works fine.

It seems like one property was in fact nil (as #Rishabh suggested). I don't think posting the whole solution is of any use for you, since it's very specific to my app.

Related

Is setting singleton to nil a good policy or it should never be set to nil? [iOS, Swift] [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I know we should completely avoid singleton, as its difficult to test them in unit testing.
Let assume someone has written a code for singleton and i have been assigned task to write unit tests for it.
Is setting singleton to nil a good policy or it should never be set to nil?
If setting to them is nil policy then,
should i make it an optional or should i crate a private setter and public getter, then later on write reset() function to make singleton nil ?
Why I want to set to nil to perform unit test on singleton class.
ok, i would like to extend this question. assuminng that its not good practise to set singleton nil. Another query in mind is, suppose someone has already written code for singleton class.
now they have assigned task to you to test that singleton class. (not the other class which uses them).
how to work on that ? as for SUT, we mostly alloc SUT in setup() method and set to nil in teardown() method.
but since it is singleton , we can not set to nil, and also in setup() me can't alloc it, we can refer to same object again and again.
First thing Singleton class should never be nil. As it's name says we are allocating memory for singleton class only once.
You Can't 'deinit' singleton class if you want to test you can do it like creating methods.
e.g if your singleton class is for like NotificationManager then create two methods subscribeForNotification() & unsubscribeForNotification() You can init or deinit object available in singleton class but not deinit singleton class.

Change to UIViewControllerTransitioningDelegate definition for Swift 3 prevents transition [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
I have been following a tutorial to add custom transitions, written for Swift 2:, but my custom transitions do not replace the existing ones.
For Swift 3 its really important to use animationController( forPresented: instead of animationControllerForPresented ( in your delegate definition.
extension DataViewController: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return PresentMenuAnimator() //your replacement
}
}
Otherwise your suggested animator just gets ignored.
This is not flagged up by the autocorrect code in Xcode.
This problem is caused by Swift 3 renamification. In particular, the Clang Importer has trouble with optional protocol methods: the compiler doesn't always match up your old declaration with the new, renamified declaration. Thus, your method becomes a useless function that will never be called: you don't get any warning from the compiler about the problem because the method you have failed to implement correctly is optional, but at runtime, Objective-C does not see your declared function as the method it is looking for, so it doesn't call it.
Here are some tips I've developed for noticing and solving this problem:
Always make your declaration in an extension explicitly adopting the protocol. The compiler will certainly not see your methods if you don't do that. (I regard this as a bug in Swift, and have filed it.)
Put the selection inside the function name and look at the Quick Help inspector on the right. If you don't see the help — that is, if all you see is your function declaration — you have not matched the delegate function correctly.
Look at the docs! In this case, https://developer.apple.com/reference/uikit/uiviewcontrollertransitioningdelegate shows the renamified signatures. And so do the headers: just command-clicking the term UIViewControllerTransitioningDelegate would have shown them to you.
When in doubt, stick the Objective-C name of the method in front of yours with an #objc(...) attribute. That allows Objective-C to see your method. It's a temporary stopgap but at least it would have gotten your code working again.

iOS Swift using getter and setter or direct access? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I'm new to Swift and iOS and I'm trying to figure out what is the recommended approach for setting and getting values. I've noticed that in the build in classes there is a lot of direct access compared to Android (where I come from). So what does iOS veterans do and why? And is there some kind of recommended approach?
In spite of being syntactically identical, accessing Swift properties is not the same as accessing Java variables, When you expose a variable in Java, like this
class MyClass {
public int val = 123;
}
you have no way of protecting it at some later time without breaking everyone else's code that reads and writes c.val variable.
Swift properties, on the other hand, let you add custom getters and setters to something that looks like a variable at the beginning:
class MyClass {
public var val = 123
}
If you decide that you want a setter later, you can change this to
class MyClass {
private var _val = 123
public var val : Int {
get {
return _val
}
set (newVal) {
precondition(newVal >= 0, "Negative values are not allowed")
_val = newVal
}
}
}
This is because when you write c.val = -321 Swift executes the code of the setter, i.e. what looks like a direct access is actually a method call.
What looks like an assignment is actually a setter, and what looks like reading a member is actually a getter. The class usually has a primitive setter that just assigns or reads values, but that can be overridden with any code you want. In addition, there are didSet / willSet where the class can add code to react to changes.
You never write code that looks like you are calling a setter or getter, but you are actually calling them.
If you find that you are executing a lot of code when a getter or setter is called, which would be unexpected to a caller, you use a function instead.

Is encapsulation in Swift as important as in other OO languages [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
When I was learning other languages such as Java, all the sample code tells you that you should always mark a field private. And the methods that do the internal stuff are also marked private or protected.
But when it comes to Swift, I see that the sample code from a lot of the tutorials (such as raywenderlich.com) seldom marks something as private. They just leave it internal (without adding any modifiers).
In contrast, all the android tutorials mark some of the fields as private and provide no getters or setters for them.
For example, I read this search bar tutorial a while ago:
https://www.raywenderlich.com/113772/uisearchcontroller-tutorial
When I was reading through it, I was thinking about: "Why did you not mark this private?"
let searchController = UISearchController(searchResultsController: nil)
I mean, it does not make sense for other classes to access the search controller of my VC. It's mine!
Question:
Why don't most, if not all tutorials provide sample code that contains private properties? Is it because iOS is more secure or something? Should I mark suitable stuff as private in production code?
I hope this is not too opinion based. In Java, you will never make a field public, right? That's just a fact - you should not make fields public. So please don't close as opinion based, it's not.
Why not everything private? There are several really common scenarios that I've seen that always favor having the variable either internal or public.
Delegate methods:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(
myCellID,
forIndexPath: indexPath);
return cell;
}
This method will be called not internally by you, but rather by the iOS system that manages and displays the tableView. The delegation pattern is widely used within iOS development.
Data exchange between two ViewControllers, where you simply want to set the other ViewController's field:
class MyVC1: UIViewController {
var flagShouldUpateColors = false {
didSet{
// some stuff
}
}
}
Then at some point you want to notifiy this ViewController that the flag should be set to true. You do that my simply acccessing it's field.
Also selectors. When I register an instance of a ViewController for some notification, I pass the name of a method that I have within the very same ViewController. It is to be called when the notification triggers. Basically what the code says is "please call this method for me when this occurs". If you say call this private method when this occurs, it wouldn't make sense would it ? How is the caller supposed to call it(aside from reflection and other unoptimized ways). Here is example:
override func viewDidLoad() {
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: #selector(self.doStuffWhenEnterForeground),
name: UIApplicationWillEnterForegroundNotification,
object: app)
doStuffWhenEnterForeground();
}
func doStuffWhenEnterForeground() {
}
Main difference between Java and Swift is in properties.
Java has no concept of properties. It has fields and if you want to allow public access to those fields you can either access them directly or through getter/setter methods.
If you create public field that needs to be protected later on you will have to use methods and thus your public API will be changed - fields are accessed without parens and methods with them.
Swift is different in that regard. You can protect your field access with getter/setter at any point without changing API. So if you have field that is part of public API you can just leave it as is (without making it private) and without having getter/setter methods attached to it.
Encapsulation in Java and Swift are of the same importance. What differs is how it is achieved (implemented). Since there is no pressure for premature encapsulation in Swift and it is only matter of adding visibility specifier when appropriate there is some lack of discipline in adding those in tutorial code where main purpose is not enforcing encapsulation, but teaching some other concepts and how-to's.
Why don't most, if not all tutorials provide sample code that contains private properties? Is it because iOS is more secure or something? Should I mark suitable stuff as private in production code?
Probably because it's simpler, save few keystrokes and doesn't add unnecessary overhead to understanding the main theme of tutorial.
Should I mark suitable stuff as private in production code?
Yes, you should do it for the same reasons you would do it in Java. Notice 2 things, however:
There is no such thing as protected.
Access modifiers in Swift work differently compared to many other languages. private restricts access to variable or function to file where it was declared, regardless of who will access them. Thus, if you have 2 classes declared in the same file, they both can see private fields of each other. On the other hand, you can't see private fields even from extension of that class if this extension in other file. It looks strange at first and you just need to get used to it.

Somes questions about Objective-C [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 8 years ago.
Improve this question
I'm a student in a internship, and i'm learning Objective-C in order to develop an IOS application. They already had an existing base of code, but some part of the code give me problems.
As the previous developer isn't in the company anymore, and because no one else know about Objective-C, no one can answer some of my questions about how the application is built, so I can't determine if it is that i don't understand, or if it's just bad practices.
Here are these questions :
1°) In some classes, i found code like this :
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated] }
This code is useless, right ?
2°) In like 9/10 methods in the project, they return (void). Is it a common pratice in Obj-C (because everything is a pointer) ?
3°) Sometimes there is the interface declaration in both header and messages files. I guess it's because you want to declare only a part in header for a future include, and to have a "private" part. But in a file, i find the following code :
In header :
#interface WebViewController : UIViewController
#properties ...
#end
In Msg file :
#import ...
#interface WebViewController ()
#end
#implementation WebViewController ...
What's the point declaring a void interface a second time in the msg file ?
4°) More, in another class, the interface is declared a second time too, but a method is defined (in the msg file). What's the point as the method is defined bellow, and is not declared in the header file ?
thank you in advance
Welcome to Objective-C :)
Not necessarily. The super class may have specific behaviour defined in it's own method implementation that would cause an issue if you didn't call it. Overriding methods means the super classes own method won't be called by default.
Added from comment: Of courser if you didn't override it then the superclass definition would get called just fine. There are 2 common reasons why you would find it overridden:
a. It's in the Xcode template so it has always been there and not been removed
b.it used to have other content but it was deleted and the method call left behind.
Yes. Although you don't explicitly return void in the method, you do need to specify some return type. If you're not returning anything then void is the right value. It's found commonly in obj-c classes as the method may respond to being called by mutating an internal ivar or property and not require a return. Alternatively the result might be to send a notification so a return value is not needed. Increasingly the use of block-based completion handlers replaces explicit value return as a way to respond to the contents of a method.
Yes, it's to give a private interface that you don't want exposed. In the case where there's nothing in the private interface it's probably there because it came with the template code from Xcode and no one removed it. You can ignore or remove.
For the one you mention with a method, while it's not required to declare private methods in an interface it makes sense from the point of view of writing readable code (a strongly endorsed concept in obj-c). Since the compiler will remove any unnecessary code it makes no difference to declare it and makes the task of reading the code and understanding the class that much easier when you or someone else returns to it later. It's a also a good place to put documentation in comments as it groups it all together.
Hope that helps. Check out the Objective-C programming guides from Apple to for more best practice tips.
1). Yes you can delete this method
2). It depends upon your requirement, whether you want a return type or not. e.g.
- (BOOL)isEmptyOrNull:(NSString*)str;
3). These are called extensions, you can read more about it here http://rypress.com/tutorials/objective-c/categories.html
Extensions are used to hide the methods from out side world(by saying hide I mean you can't find those methods with your eyes)
4). Methods define in implementation file are not visible to a programmer, it's just like private methods in java but in ObjC there is no such thing like private method. Read this thread for private methods Best way to define private methods for a class in Objective-C

Resources