Blog Archives

Inter-Process Communication on Mac – Know How part4(Distributed Notifications)

In  Part 1 of this blog series we discussed about various techniques available for Inter-Process Communication (IPC) on Mac OS X.

As discussed in previous blog  Distributed notifications work as follows :
1. A notification center manages the sending and receiving of notifications. It notifies all observers of notifications meeting specific criteria.
2. The notification information is encapsulated in NSNotification objects. Client objects register themselves with the notification center as observers of specific notifications posted by other objects.
3. When an event occurs, an object posts an appropriate notification to the notification center.

Posting a distributed notification is an expensive operation. The notification gets sent to a system wide server that then distributes it to all the processes that have objects registered for distributed notifications. The latency between posting the notification and the notification’s arrival in another process is unbounded. In fact, if too many notifications are being posted and the server’s queue fills up, notifications can be dropped.

Let’s look at a simple code to send and receive distributed notification. Read the rest of this entry

Advertisements

Inter-Process messaging in cocoa

Objective-c supports an inter-process messaging system. An application running on different machines and on same computer can send message’s to each other.

Objective-c classes use for inter-process messaging are as follows:-

NSConnection
NSPort
NSMachPort
NSMessagePort
NSSocketPort
NSProxy etc..

NSConnection object manage the communication between objects and normally run in the background.

NSPort object represent the communication channel. Its an abstract class and sending and receiving messages handle through port.

NSProxy is an abstract superclass and typically a proxy forward the message to real object and load the real object.

Example: A program using NSSocketPort, NSConnection to send message from one computer to another computer. Read the rest of this entry

Inter-Process Communication on Mac – Know How part3 (Apple Events)

In  Part 1 of this blog series we discussed about various techniques available for Inter-Process Communication (IPC) on Mac OS X.

As discussed in the previous post Apple Events are the only IPC mechanism which is universally supported by GUI applications on Mac OS X for remote control. Operation like opening a application or telling a application to open a file or to quit etc. can be done using these.
AppleScript is a scripting language built on top of Apple Events which can be used using scripting bridge in a Mac application.

Here in this blog we will see the implementation  of IPC using apple events. Read the rest of this entry

How to detect and identify mounted and unmounted USB devices on Mac using Cocoa

There could be a situation in which we have to notify the application about mounting and un-mounting the USB and also to identify the USB i.e on which path it is mounted, what is the type of USB e.g I-Pod, I-Phone , Pen Drive etc.

First let’s see how can the application be notified of USB mounting and un-mounting.
To get the notification for mounting and un-mounting  of the USB device we can create 2 notifications:

Notification for Mountingthe USB device

[[[NSWorkspacesharedWorkspace] notificationCenter]addObserver:selfselector:@selector(deviceMounted:)  name: NSWorkspaceDidMountNotificationobject: nil];

Notification for Un-Mountingthe USB device

[[[NSWorkspacesharedWorkspace] notificationCenter]addObserver:selfselector:@selector(deviceUnmounted:)  name: NSWorkspaceDidUnmountNotificationobject: nil];

Once we get the notifications, now is the task to get the volume path on which the USB gets mounted.
This code will give an array of volume paths for each mounted USB

NSArray* devices = [[NSWorkspacesharedWorkspace] mountedRemovableMedia];

Now After getting the mounted paths, let’s identify the USBs
Every device has a VendorId, ProductId, ReleaseID and Name configured by the manufacturer. For ex. if the mounted USB is a I-Pod then it can be identified using the combination of it’s VendorId and ProductId. To get these attributes, Add IOKit framework to the project and import following headers in .m file. Read the rest of this entry

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

Inter-Process Communication on Mac – Know How part2 (Shared Memory)

In  Part 1 of this blog series we discussed about various techniques available for Inter-Process Communication (IPC) on Mac OS X.

As discussed in earlier blog Shared Memory is a implementation for IPC where a memory section is shared between different processes.In other words process A writes to this memory and B can read from this memory, or vice verse. This is fast and data doesn’t have to be copied around. The downside is that it’s really difficult to coordinate changes to the shared memory area.

Here in this blog we will see the implementation  of IPC using shared memory. We will create a server and client and will create a communication channel for data transfer between two processes.

First let us look at the basic implementation of Server using Shared memory Read the rest of this entry

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

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

%d bloggers like this: