Blog Archives

How to connect IBOutlet and IBAction in Swift language ?

Step 1. Create new project and select Cocoa Application Template.

-> Template automatically create the AppDelegate.swift , MainMenu.xib files and other stuff.

Step 2. Select the MainMenu.xib and open it. And then drag and drop the NSButton and NSTextField from the object library.

Step 3. Create IBOutlet and IBAction for NSTextField and NSButton respectively:-

-> Select the AppDelegate.swift file and open it. You will find two methods in this file such as:

func applicationDidFinishLaunching(aNotification: NSNotification?)
func applicationWillTerminate(aNotification: NSNotification?) Read the rest of this entry

Advertisements

Swift Programming Language – Part 1

This blog will explain some concepts of swift programming language which are as follows:-

1. Basics

2. Operators

3. String and Characters

4. Collection Types

5. Control Flow

6. Functions

All topics will be covered with example.

Basics

Swift is a new programming language for iOS and OS X application developers. Swift have same basic DataTypes as in Objective-C and C.
There is some new features which is not available in Objective-C and C as follows:-

a.) Tuples

Using Tuples a function can accept grouping of values and also return multiple values.

b.) Optional types

Its a most powerful feature of swift programming language. Optional are similar to using nil in objective-C. Its not only use with class type, can also use with any type.

Constants and Variables

The value of constants can not be changed once its initialized but the value of variable can be modify after initializing it.

How to declare a variable and constants:-
“let” keyword is use to declare a constant and “var” keyword is use to declare a variable.

Example: Below example demonstrate how to declare and initialize a constant and variable.

Step 1 Create a command line tool project.
Step 2 Open a main.swift file and code as below:

    import Foundation
    let height = 200            // Constant
    var width = 400             // Variable
   // Statement will log the output on console like NSLog in Objective-C
   println("Width = \(width) and Height = \(height)") 

Output:
      Width = 400 and Height = 200

In variable we can reassign new value like as

    import Foundation
    let height = 200         // Constant
    var width = 400          // Variable
    width = 300
    // Statement will log the output on console like NSLog in Objective-C
   println("Width = \(width) and Height = \(height)") 

Output:
      Width = 300 and Height = 200

But we can not assign new value to constant like as

    import Foundation
    let height = 200            // Constant
    var width = 400             // Variable
    height = 300
    // Statement will log the output on console like NSLog in Objective-C
   println("Width = \(width) and Height = \(height)") 

Error “Can not assign to ‘let’ value height”

we can also declare multiple variable and constant like as

var a = 2, b= 3

Note: In swift language , a statement is allow without semicolon. But semicolon is require in case of multiple statement in single line.

Type Annotations

It means specify the data type of variable at time of declaration like as:

import Foundation
var width : Int = 20
println("Width =  \(width)")

Output:
    Width = 20

Multiple variable declaration:

import Foundation
var width , height: Int
width = 20
height = 30
println("Width = \(width) and Height = \(height)") 

Output:
      width = 20 and Height = 30

Note:
a) if we declare like as in multiple variable

         var width , height: Int = 20
         It will give error such as “Type annotation missing in pattern”

b) You must initialize variable before using it.

         import Foundation
         var width : Int
         println("Width =  \(width)")

It will give error such as “Variable width used before being initialized”

Tuples

Tuples use to group multiple type of values in single compound value. Eg:

    import Foundation
    // Declare variable student of Tuple type which have two values such as name and age
    var student = ("Ram" , 25)
    var (name , age) = student
    println("Name is =  \(name) and Age is = \(age)")

Output:
Name is = Ram and Age is = 25

Optionals

Optional means variable may have a value or it may not have. It use to declare a variable with value nil.

Eg:
Program 1.

    import Foundation
    // Option name variable declaration
    var name : String?
   if name
   {
        println("Name is =  \(name)")
   }
   else
   {
        println("Name is Nil")
   }

Output:
      Name is Nil

Program 2.

    import Foundation
    // Option name variable declaration
     var name : String?
     name = "Ram"
     if name
     {
        println("Name is =  \(name)")
     }
     else
    {
        println("Name is Nil")
    }

Output:
      Name is = Ram

Operators

Operators are unary , binary and ternary.

Unary operator which apply on one operand. Binary operator which apply on two operand. Ternary operator which apply on three operand.

Assignment Operator

Assignment operator assign value of right operand to left operand.

Eg:
var x , y : Int

x = 10 y = 20

x = y // Here x contains 20
we can assign tuple as well to left side such as

var (x, y) = (10, 20) // Here x contains 10 and y contains 20

Arithmetic operators

Addition (+) , Minus (-), Multiplication (*), division (/)

Behave same as in c or in objective-c.
In swift , + operator can use to concatenate the String.

Eg:

import Foundation
// Option name variable declaration
var firstName = "Ram", secondName = "Shyam"
var fullName = firstName + secondName
println("Name \(fullName)")

Output:
    Name RamShyam

Remainder operator (%)

Remainder operator in swift can also apply on floating point remainder calculation.

Increment/Decrement Operator

Behave same as in c or in objective-c.

Compound assignment operator

Behave same as like c and objective-c language.

Eg:
var c = 2

c += 3 // Here c contain 5

Comparison Operator

Swift have all comparison operator like in c and objective-c:
Less than (<), Greater than (>) , Equal to (==), not equal to (!=) etc

Nil Coalescing Operator

The nil coalescing operator syntax is like as (a ?? b). It means if a is nil then b will be use.

Eg:

var defaultValue = “DefaultValue”
var anotherValue : String? // Initialize as nil var actualVale = anotherValue ?? defaultValue

// Here actualValue

variable contains “DefaultValue” string.
if anotherValue var is not nil then actualValue variable contain the anotherValue. Range Operator
Swift includes two range operators.
Closed Range Operator
Closed range operator syntax is (a…b). It will run from a to b.
Eg:

    import Foundation
    var a = 1, b = 2
    for value in a...b
    {
        println("Value is \(value)")
    }

Output:
      Value is 1
      Value is 2

Half-Open Range Operator
Half-Open range operator syntax is (a..<b). It will run from a and upto less than b Eg:

         import Foundation
         var a = 1, b = 2
        for value in a..<b
        {
            println("Value is \(value)")
        }
Output:
      Value is 1

Logical Operators

Logical operator is similar to logical operator in c language. Logical And (&&), Logical OR (||), Logical Not (!)

Strings and Characters

String is a collection of characters. In swift language , String data type use for string type value.

Eg:

// String type initialized
// Optional String type
// String type initialized
// Initializing empty string

if we initialize a string with “var” keyword that it means it is mutable string and if we initialize string using “let” keyword that it means immutable string.

Character can be declare and define using the Character keyword as annotation.

Eg:
var singleChar : Character = “A”

var name = “Any Name”
var name : String?
var name : String = “Any Name” var name = String()

String Concatenation
String can be combined using “+” operator like as

var firstName = “Jhon”
var scondName = “Player”
var fullName = firstName + secondName // it will contain JhonPlayer

Counting Characters

There is countElements function which we call on string to count elements.

Eg: countElements(fullName) // It will return 9

we can compare sting using comparison operator (==). And we also have function hasPrefix and hasSuffix to check prefix and suffix.

Collection Types

Swift have two collection types: Array and Dictionary. Collection type can also mutable and immutable.

Array
Array store multiple values of same type. We can declare array like as: var list : [String] = [“A”, “B”] // Its a string type array

To count number of items in an array use count function. And to check whether array is empty or not use isEmpty function.
To insert at specific index swift provide insert method.

eg:
list.insert(“Value”, atIndex:0)

we can iterate an array using for-in loop.

Dictionary

Dictionary store multiple values of same type in key value pairs.

Dictionary can be declare and define like as:

Eg:
var someDic : [String : String] = [“Key1” : “Value1”, “Key2” : “Value2”]

We perform following operation on dictionary such as

updating dictionary, count elements, check whether is empty or not.

Control Flow

There are following elements of control flow:
for, do-while, while, if, if-else, switch, break, continue so on.

Swift add for-in loop and also make switch statement powerful comparison of c language.

Loops

Some basic loop are same like in c language. Below is the example of for-in loop which is new in Swift language.

Eg:- for – in loop

    import Foundation
    var a = 1, b = 2
    for value in a...b
    {
        println("Value is \(value)")
    }

Output:
      Value is 1
      Value is 2

we can use _ if we are not going to use value like as

Eg:
for _ in a…b

{

println(“Value Blank”)

}

Switch

Switch statement is faster than if – else statements. Switch contain some matching pattern. Its syntax is:

switch someValue

{

case value1:

}

statement case value2:

statement default:

statement

In Swift language, if we don’t use break statement in case then it will not jump to next case like in C language.

Eg:

import Foundation
var a = 1, b = 2
for value in a...b
{
    switch value
{
     case 1:
        println("Value 1")
     case 2:
        println("Value 2")
     default:
       println("No Value")
}
}

Each case must have alteast one statement to execute else will give compile time error.

We can use Tuple in test cases and also can use where clause.

Fallthrough

To fall through to next case in swift language we use fallthrough keyword.

Eg:

import Foundation
var a = 1, b = 2
for value in a...b
{
    switch value
{
     case 1:
         println("Value 1")
         fallthrough;
     case 2:
         println("Value 2")
     default:
         println("No Value")
}
 }

For value = 1, two cases will execute case 1 and case 2.

Functions

Functions are block of code which perform some specific task. Function can take parameter as input and return some parameter/parameters as output.

Below is the example of function which take name as parameter and print the name. Eg:

    import Foundation
    func printName(name :String)
    {
        println(name);
    }
    printName("Jhon") 

Function returning value:
    import Foundation
    func printName(name :String) -> String
    {
        return name + "Player"      // Concatenating string
   }
   println(printName("Jhon"));

we can pass the multiple parameter using comma separation.

// Function calling

Functions with returning Tuple as parameter:

import Foundation
func printName(name :String) -> (firstName : String, lastName: String)
{
    var components: Array  = name.componentsSeparatedByString(" ")
    var firstComponent: String  = ""
    var secondComponent: String = ""
    if !components.isEmpty
    {
        firstComponent = components[0];
        secondComponent = components[1];
    }
    return (firstComponent, secondComponent)
}
var name = printName("Jhon Player");
println("First Name is \(name.firstName) and Last Name is \(name.lastName)"); 

Function with In-Out Parameter:

If you want to modify parameter value and preserved that modification after function exit then we supply parameter as In-Out parameter.

Eg:

import Foundation
func swap(inout a: Int, inout b: Int)
{
    var temp = a 
    a = b
    b = temp 
}
var a = 10, b = 20
swap(&a,&b)
println("A = \(a), B = \(b)")

Output:
      A = 20 , B = 10


Written By: Yogesh Arora, Software Engineer, Mindfire Solutions

Objective-c 2.0 features

Synthesize take place by default:-
In previous version , if we declare properties then we have to synthesize that property. But in modern
objective-c, we don’t require to synthesize the proeprty.
Eg:-
In modern objective-c,

@Interface MyClass : NSObject

@property (nonatomic, retain) NSString* myProperty;

@end

@Implementation MyClass

//Don’t require to synthesize the property in modern objective-c. Compiler automatically
synthesize it.
@end

Method ordering:-
In previous version, if method call before defining it and without declaring it, then it will give compile
time error. But in modern version if method invoke before definition and without any declaration ,then
complier will give no error.

NSNumber literals:-
In previous version, the initialization of NSNumber objects require class method.

Eg:- NSNumber* number =  [NSNumber numberWithInt:12];

But in modern objective-c  , NSNumber  objects can initialize like this:-
NSNumber* number  = @3;
For character,
NSNumber * number  = @’A’

Array Literals:-
In modern objective- c initialization of array literals   have less typing.

Eg:- As per previous version:-
NSArray* array = [[NSArray alloc] initWithObjects:@”A”, @”B” , @”C”, nil];
As per  modern objective-c:-
NSArray* array = @[@”A”, @”B”, @”C”, @”D”, @”E”];

Accessing array elements:-

As per previous version:-
NSString*  element = [array objectAtIndex:0];

As per modern objective-c:-
NSString* element = array[0];

The new syntax using index subscripting.

Creating mutable array as per new syntax:-
NSMutableArray* mutableArray = [@[@”A”, @”B”] mutableCopy];

Dictionary Literals:-
Initialize   dictionary as per previous version:-

NSDictionary* dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:object1, key1, object2,     key2, nil];

Initialize dictionary as per modern objective-c:-

NSDictionary* dictionary =  @{Key1: object1, key2:object2};

As with array, subscripting can also use in referencing dictionary items in modern objective-c.

object1  = dictionary[Key1];

instancetype:-
Its a return type keyword thats return an instance of a class they are called on.
In modern objective-c use instancetype instead of id where appropriate. It provide more type safety
instead of id.
Eg:-
Suppose there is a class

@Interface MyClass: NSObject

+(instancetype) methodA;
+(id) methodB;

@end

@Implementation MyClass

+(instancetype) methodA
{
return [[[self class] alloc] init];
}

+(id)methodB
{
return [[[self class] alloc] init];
}

@end

The methodA return an instance of kind MyClass and methodB return an instacne of id.
So suppose if we write any method and wrote some code like:-

[[MyClass methodA] count];

And

[[MyClass methodB] count];

then first line of code will give compile time error becuase no count method is declare and define in MyClass, but second line return id type object and compile will not give any warning in this case.


Optional garbage collector and fast enumeration:-

Objective-c 2.0 have optional garbage collector option and also have fast enumeration  feature.

Written By: Yogesh Arora, Software Engineer, Mindfire Solutions

Access/control scriptable application using scripting bridge and Cocoa

ScriptingBridge framework in Cocoa can be used to access features from any scriptable application. In this article I will discuss how to access the features of iTunes such as current playing track, duration of the track, playlists etc by using ScriptingBridge.framework in a Cocoa Application. However you can follow the same steps to allow your application to interact with any other scriptable application.

Read the rest of this entry

How to get selected text and its coordinates from any system wide application using Accessibility API?

In my previous post, I had discussed about accessing the text value from any system wide application by using Accessibility API. Now going further,  you may want to access only the selected text or the position of selected text, we will discuss about it in this article.

Read the rest of this entry

Working with JNI on MAC OSX platform

 In this post, I will discuss about the Java Native Interface(JNI) and Java Virtual Machine(JVM) on Mac OSX.

JNI stands for ‘Java Native Interface’. It will act as an interface between java and other languages. JNI allow a code written written in  languages like C, C++,  Objective-C etc to use java libraries and from java code to use other language code.It means you can call java methods from other languages using JNI and vice versa. Java native methods are flagged by the keyword ‘native’.

Advantages:

  • Use the existing library,
  • Speed of execution,
  • Invoke API functions from product that is developed in C or C++ from a java client and vice versa.

Disadvantages:

  • Run time errors debugging is difficult in native code.An applet can’t call a native methods.
 You can’t say ‘write once run anywhere’.

Introduction to JVM
JVM stands for ‘Java Virtual Machine’. Java Virtual Machine or JVM is a platform independent execution environment that converts Java byte-code into machine code(binary). JVM function is to load the appropriate class files for executing a java program, and then to execute it. Read the rest of this entry

Accessing text value from any System wide Application via Accessibility API

Suppose, I want to create a application which will monitor the typing and say if “macdevelopers” is typed anywhere be it in TextEdit or Mail etc. the application will perform a operation for example automatically opening the website in a browser.

The text value from any System wide Application can be accessed using the Accessibility API. In this article I will discuss about accessing the text value from any application like Text Edit or other applications if its current focused element is some text field or text view in it. Thus using this you can implement the functionality to access the active application’s text field value. Read the rest of this entry

Undo/Redo in a Cocoa Application (Example to Undo/Redo addition & deletion of rows in a table view)

Undo/Redo functionality in a Cocoa application – NSUndoManager

This article will give you an overview of adding undo and redo functionality to a cocoa application by an example that undo/redo addition and deletion of rows in a TableView.

Lets start with How Undo Manager works?
As per Apple’s Reference Guide “You register an undo operation by specifying the object that’s changing (or the owner of that object), along with a method to invoke to revert its state, and the arguments for that method. When performing undo an NSUndoManager saves the operations reverted so that you can redo the undos.” Read the rest of this entry

Protocol Buffers with Objective-C

What are Protocol Buffers? Protocol Buffers are a way of encoding structured data. Protocol buffers are a flexible, efficient, automated mechanism for serializing structured data like XML, but smaller, faster, and simpler. You define how you want your data to be structured once, then you can use special generated source code to easily write and read your structured data to and from a variety of data streams and using a variety of languages. You can even update your data structure without breaking deployed programs that are compiled against the “old” format.

How to use Protocol Buffers with Objective C?

Read the rest of this entry

How to check if a file is open or not using Cocoa/Objective-C?

First let me make it clear that we are not discussing about finding if a application is running or not, which can be found out very easily by using  [[NSWorkspace sharedWorkspace]  runningApplications].

We are going to discuss how if we can, get the information about a file that whether it is open or not through a Cocoa Application.

Before going further down in the topic let us consider following scenarios to understand the need of the discussion.

1. A Cocoa application might be concerned with performance enhancement and for that it might need to find and list out the opened files.

2. A application might need to find the port associated with a daemon.

3. A application might need to constantly monitor a document or documents in a particular directory and when user close that document after editing, it has to perform certain tasks.

Read the rest of this entry

%d bloggers like this: