Open Terminal from Xcode

I love Xcode as an IDE for macOS and iOS development. But it has its own set of limitations. One feature I miss a lot is Opening a Terminal window from the Xcode into the same directory of the project. This will save lots of time.

Every time you want to run a git command or cocoapods or say any xcode build command – Opening a Terminal manually and changing the directory to the project directory takes at the least 30 seconds to a minute. Now what if I say you can do this

Now, What if I say you can open a Terminal window and get to the project directory  in 1 second or say with a shortcut key?

YES! One shortcut.

This is how you do it. It’s a one time setup.

1. Create a 2 line shell script and give the file execute permission.
2. Go to Xcode Preferences.
3. Add a Behavior in Xcode. Name it and give a shortcut key.
4. On the right side details pane check the Run option.
5. From the adjacent drop-down menu choose the script you just saved in step 1.

Here’s the video on how to do it.

Script:
#!/bin/bash
open -a Terminal "`pwd`"

Command to give execute permission:
chmod +x /path/to/the/open_terminal.sh

If you are lazy like me here’s the gist, download and use it:¬†https://gist.github.com/itsdamslife/9532d757676b1f3c9b25f3959128367c

Hope this is helpful.

Happy coding ūüėČ

inspiration courtesy: The in-built Terminal of Visual Studio Code by Microsoft


Damodar Shenoy's DEV Profile

Advertisements

Deep copy and Shallow Copy

This is an important concept of computer science. You may have heard it very less in your day-to-day work life but your work will directly or indirectly relate to this one of the main concept of memory management. Let’s dive into this.

Here is scenario – Assume you have a team of 5 members. You have created a document on Google Drive and shared the link to the document with your team members.

Now how the doc is used / consumed is upto the members. Primarily there are two ways:

  1. One is : Using the online version directly to read/update or if someone updates you get the latest update directly. One can see the changes live.
  2. The other way is: Download a copy to your local system and use it as per your wish, manipulate it update it without altering the original copy which is on the cloud.

Thats it. If you know the difference between the 2 above,You got the concept! The first one is Shallow copy of the document and the second one is Deep copy of the document.

Now using this analogy let me explain you the memory management concepts of Objective-C and Swift.

  • strong : Members who have doc added to their own drive. Even if original is deleted the doc is not deleted. The reference link still points to the doc
  • weak : Members who have access to the doc will be informed upon deletion of the doc. Now the reference link will be invalid. It will point to nil.
  • assign :¬†Members who have access to the doc will NOT be informed upon deletion of the doc. Now the reference link will be invalid. App crashes if the link is accessed.
  • copy : Members download copy of the doc to their own system. Does not effect if either of them are modified or deleted. Takes up additional memory unlike the above 3 which are referenced to same memory location. Mutable copy is when document is downloaded with RW permissions.

The 4 statements above may or maynot hold good for Google drive but only used to explain the concept.

Pros & Cons:

Shallow copy

  • Doc link which is stored in the cloud
  • Owner and admins is the strong reference
  • Non admins will have weak reference
  • Changes to the document will be notified to every member

Deep copy

  • Document downloaded to local system
  • Consumes additional storage
  • If some one changes in the cloud does not effect your local system
  • Whatever you change locally does not effect cloud version

I made up this analogy because I found it easier to link both the concepts for understanding. Let me know if you find this difficult or missing. Please share your comments below.

happyCoding();


Dam's DEV Profile

Obj-C — Swift — Obj-C

This is one of the rare scenarios one might get into, but the problem and its solution are unique and the simplest one here.

  • Have you come across a scenario where you felt the need for an additional method in a class inside a framework (one of the Pods you added) to achieve your work?
  • Is the library implemented in Objective-C?
  • Is your legacy code in Objective-C and now you are strategically moving to Swift?

Today at work my friend, Vinodh, asked me this:

“I have a pod framework which is in Objective-C, I need to add a functionality but needs to be used in Obj-C for now and may be used in Swift file in future. What is the best way to do this?

Let us say we have a class called Person inside one of your pod frameworks. This Person class has name, age and gender as properties, with a function to format the name.

// Objective-C header file of Person class
#import 

typedef enum : NSUInteger {
    male,
    female
} Gender;

@interface Person : NSObject

@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) Gender *gender;
@property (nonatomic, strong) NSUInteger *age;

- (NSString*)formattedName;

@end

// Objective-C Implementation of Person class
@implementation Person

- (NSString*)formattedName
{
    return [NSString stringWithFormat:"This is %@",self.name];
}

@end

When the formattedTitle method is called on a person object with value for name property ‘Vinodh’ it would print like “This is Vinodh”.

Now we need to extend this Person class with another method say a new format which tells the age along with the name.

In classic Objective-C style it would be adding a category to Person class, Importing this category wherever you need this new method. This would have been the best way before Swift was introduced.

But there is a disadvantage if new developer join unitl and unless (s)he imports the category header, code completion will not show the new method. Probably the new developer will end up writing the same method creating a new category again. This is a problem.

Swift to rescue. Do the following:

  • Create a Person class extension and write the needed method
  • Now create a protocol and declare the method signature
  • Now prefix the protocol with @objc to make this available in Obj-C files

Here’s how you do it.

@objc protocol Formats {
    func getFormattedName(with ageHidden: Boolean) -> String
}

extension Person: Formats {
    func formattedName(with ageHidden: Boolean) -> String {
        let formattedString: String = ageHidden ? "This is \(self.name)" : "This is \(self.name) aged \(self.age) years."
        return formattedString
    }
}

Now wherever you type [personObject form… in Obj-C or in personObject.form… in Swift the code complete will show you both the methods one Person class another from the extension we added.

Love to hear more stories from your side. Please do share in comments.

Happy Coding!

Swift meetup

After a long time attended a meetup. And this was on the topic which I work on day to day – Swift programming language.

The meetup overall was good. Got to learn couple of new things – DispatchGroups, Swift Runtime and the thing that we can have our own Swift’s virtual environment just like virtualenv in Python, for swift its called virtualswift.

The most useful talk for me was on measuring performance in swift by Mayur Dhaka in which I can use immediately is DispatchGroups.

DispatchGroup primarily avoids the code shifting to right while using nested blocks like completion handlers.

From what I understood is DispatchGroups are the thing which can be used to group a logical set of background operations into one unit. It has very few APIs. According to Apple :

DispatchGroup().enter() – to indicate the block has entered the group.

DispatchGroup().leave() – to indicate the block in the group has completed.

DispatchGroup().notify(...) – to schedule a block or a work item to be submitted to a queue when a group of previously submitted block objects have completed.

DispatchGroup().wait(...) – waits synchronously for the previously submitted work to complete.

Basically DispatchGroup is to synchronize and track a set of tasks which are logically grouped and executed according to your requirements.

Hope this gist will help you get to know something new and explore more if interested.

swift-small

Protocol oriented Programming (PoP)

This post is a part of my blogpost series while learning Swift and Programming paradigms. First part on Functional Programming can be found here.

Protocol oriented programming (POP)¬†can be said as¬†as – a way to adhere the “Program to interface not to implement” principle¬†– which is one of the basic design principles of software development. Structure your code such that you¬†define interfaces first then make the classes implement it. Define interfaces¬†using protocols and then make classes implement them. POP is just another technical term for the interface programming in Swift programming language.

Yes! There are additional advantages of POP in swift using “Extensions” along with protocols in Swift.

Let us discuss this with a classic example – Shapes and its classes.

Any shape has area. Every shape needs to be drawn on some canvas. Typically an average programmer thinks:

  • Let’s have a base class named Shape.
  • Let’s derive all other concrete classes from Shape class.

The first and foremost disadvantage of this solution is all concrete class inherits everything from base class whether its needed or not. Along with that multiple inheritance is not possible and moreover its a bad way.

In a practical world as the product grows its code grows and there will be a lot of overhead built over a period of time.

Here comes Protocol Oriented Programming – creating interfaces

This is link to Xcode playground @ github Рgiving a typical example of POP. Please go through the code before proceeding to understand the advantages.
Some plus points of POP :

  • No overhead of base class.
  • Protocol extensions are a great way to give default implementation.
  • Classes can conform to multiple protocols also¬†use their default implementations without overhead of inheritance.
  • Restrict access ONLY to specific functionalities of an object.
  • Protocols can be conformed¬†by structures & enumerations¬†in Swift. Class-Only protocols can¬†also be defined
    [protocol TheClassOnlyProtocol: class { ... }]

    .

  • Protocols can be used as a type for variables, which¬†is more dynamic than declaring variables¬†with concrete classes.
  • Delegation works as it used to¬†in Objective-C.
  • Protocols can be used in Collection types
  • A Protocol can inherit from multiple other protocols (multiple inheritance)

This is my understanding of POP. Please do share your comments below.

Hope you found this post useful to some extent.

What is Functional Programming?

For quite sometime now I am on¬†a new programming language from Apple – Swift. Apart from the hype Swift got¬†there are¬†multiple¬†programming paradigms that I got introduced¬†to –¬†Functional Programming (FP), Protocol oriented programming (PoP).
swift

I was little curious as I knew what functions are and what protocols are used for especially in objective-C, and my mind asked me few questions –

  • What are¬†Functional Programming and Protocol oriented programming?
  • Is swift a Functional Programming language or a Protocol oriented programming language?
  • Is it mandatory¬†to learn¬†in Functional Programming or¬†Protocol oriented programming to code in Swift?
  • What is¬†the right way?

Browsing through some websites and reading few books, this is what I understand. In this post I will be sharing my thoughts & understanding on FP and a subsequent post on PoP.

Q: What is Functional Programming? Answer:¬†(In non-developer’s term) Functional Programming is a way of how you code your solution, it’s a philosophy, it’s not related to any specific programming language.

Technical Answer: Functional programming is a way of programming where focus is on designing functions and their interactions rather than on data unlike Object Oriented Programming(OOP) where focus in on designing classes around data.

A functional programming language supports and encourages programming without side-effects. FP is a way in which you code only pure functions with all objects used in the function are passed as input parameters and all results are defined as output/return objects. In here, Functions are always pure and deterministic.

Now, what are pure functions? Answer: Functions that returns same value for given set of input values at any given point in time. These functions never modify the input values, never access, consume or modify anything outside of its scope.

Technical Answer: The result cannot depend on any hidden objects/values/state that change over a period of time. The function, In the process of execution, cannot cause any semantically observable side effects, like mutation of mutable objects or state change of any other objects.
Following holds true for FP:

  • In FP the focus is on how you design functions rather than modeling the data.
  • In FP utmost preference is given to immutability. FP hates mutating data.
  • In FP results are always same for same values supplied.
  • Functions in FP does not change any values supplied to it, neither change values outside of scope. Input parameters are only¬†consumed but not modified.
  • In FP like Swift and Scala results are most of the time return in containers/optionals. (Yes, I dug into Scala programming language concept to understand few concepts¬†of FP. Optionals in Swift are ‘inspired’ from Monads from Scala ūüėĬ†)

Advantages of Functional Programming:

  1. You definitely know what functions do and what they return. No side-effects.
  2. You need not worry much about wrapping data into threads, mutex and locks.
  3. Helps in writing lots of Unit test cases, increasing the code coverage.
  4. Modules can be isolated and independent from each other.
  5. Crash free: Functions return values wrapped in containers [Swift, Scala]

Keeping in mind all of this 2 questions raise in mind:

  1. Can we adopt functional programming in Swift? Yes, Definitely!
  2. Can we build iOS Apps in Swift completely with FP philosophy? Partially Yes. Why? Given my experience with the MV-X (MVC, MVVM, etc.,) patterns used in iOS app development access object properties and mutating datasources somewhere in the code is a must and cannot be avoided. So it is up to a developer to use their creativity to design functions or some modules in an app which adhere completely to FP.

I am new to FP¬†and still experimenting with it, trying to¬†understand it still more deeply. I also thought of adding few code snippets in this post to clearly explain and convert¬†Impure functions into Pure ones, but surely we can discuss this in comments.¬†Let’s discuss in¬†comments section about these¬†interpretations and understandings.

Keep visiting this blog for more programming stuff. Next post on Protocol oriented Programming.

Referred links which helped me understand:

Rotate Scale Flip – NSImageView

This is a problem which I have fiddled a lot to solve. Sometimes NSImageView objects seems to behave strangely when you rotate them and try to reposition it inside its superview.

The Problem:
I had an NSImageView as subview of another NSView. There where slider controls to scale and rotate the subview as and when required. I also had horizontal and vertical flipping options. So when I played around with it, the subview started acting weirdly.

I had used [subview setFrameCenterRotation:angle]; to rotate the subview.

For flipping NSAffineTransform scaleXBy:yBy: was helpful. Scaling I had set the imageScaling flag,
so that I just have to set the frame and NSImageView takes care of it by itself.

Now why is this acting weirdly? Seems all fine. All proper apis have been used. After some brain wracking and a little help from OpenGL transformation application, I found out the solution.

If you have rotated a image view, before doing any other transformation rotate it back to zero angle and the apply the transforms and then rotate it back to required angle.

Code for flipping images:

- (void)flipImageVertically:(NSImageView*)imageView
{
    NSAffineTransform *flipper = [NSAffineTransform transform];
    NSSize dimensions = [imageView frame].size;
    NSImage *aFrame = [imageView.image copy];
    [aFrame lockFocus];
    [flipper scaleXBy:1.0 yBy:-1.0];
    [flipper set];
    [aFrame drawAtPoint:NSMakePoint(0,-dimensions.height) fromRect:NSMakeRect(0, 0, dimensions.width, dimensions.height) operation:NSCompositeCopy fraction:1.0];
    [aFrame unlockFocus];
    [imageView setImage:aFrame];
    [aFrame release];
}


- (void)flipImageHorizontally:(NSImageView*)imageView
{
    NSAffineTransform *flipper = [NSAffineTransform transform];
    NSSize dimensions = [imageView frame].size;
    NSImage *aFrame = [imageView.image copy];
    [aFrame lockFocus];
    [flipper scaleXBy:-1.0 yBy:1.0];
    [flipper set];
    [aFrame drawAtPoint:NSMakePoint(-dimensions.width,0)
    fromRect:NSMakeRect(0,0, dimensions.width, dimensions.height) operation:NSCompositeCopy fraction:1.0];
    [aFrame unlockFocus];
    [imageView setImage:aFrame];
    [aFrame release];
}

Hope this helps.