Sunday, 1 March 2015

Comparisons to YES are broken

This post is inspired from the eye-opener article -> bignerdranch.

I always had this question, Why does Objective-C need a BOOL when C gives it a free bool, which effectively works the same?.

Well, I couldn’t have been more wrong. BOOL and bool are entirely different beasts.

BOOL is a typedef, defined at /usr/include/objc/objc.h (Also available here)

typedef signed char BOOL;

Similar to, Boolean, which is defined at /usr/include/MacTypes.h (Also available here)

typedef unsigned char Boolean;

Also, YES and NO are macros for 1 and 0. Reference

#define YES (BOOL)1
#define NO (BOOL)0

This means that our usual comparisons might fail. Example:

12 == YES

For more such examples, look at bignerdranch.

The thing to note is that, you should be careful about the same comparisons for Boolean too.

Friday, 9 January 2015

Exchange variables in swift with an operator

Aim is to create an operator <-> to exchange two variables. The two variables can be of any type, but they should be of the same type (Obviously!).

We start by declaring an infix operator <->
infix operator <-> {}

Now we provide a definition for the operator using a generic function.
func <-><T>(inout a: T, inout b: T) {
  swap(&a, &b)

That’s it!

The following swift powers have been tested in the snippet above
1. Custom operators
2. In-out variables
3. Generic functions

We can test the operator like:

var a = 2, b = 4
a                            2
b                            4
a                            4
b                            2

var ab = "a", ba = "b"
ab                            a
ba                            b
ab                            b
ba                            a

Do notice that the operands of the operator <-> should be declared variable (var) for the exchange to work.

Edit: From +Rogier Pinkers's comment, the implementation for the operator has been changed with the inbuilt function to exchange two variables. Thanks +Rogier Pinkers!

Wednesday, 7 January 2015

How to check if a UIViewController is being dismissed/popped?

To know if your UIVIewController is being dismissed or popped, you can ask your UIVIewController if it is being dismissed or being moved from it’s parent UIVIewController.

- (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];
  if (self.isBeingDismissed || self.isMovingFromParentViewController) {
    // Handle the case of being dismissed or popped.

This has been documented in UIVIewController.h at lines 270-275 (iOS 8.1, Xcode 6.1.1).

Via StackOverflow