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

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

Simple HelloWorld Program in GTK# 2.0 Mono Develop?

MonoDevelop is cross platform IDE to develop desktop application for Linux/windows/Mac OSX.

GTK:-

1. GTK (GIMP ToolKit) is a library to create graphical user interface. GTK is an object oriented programmers interface. Its completely written in C.

2. GTK# is wrapper over the GTK+ for the C# programming language. Application built using GTK# can run on multi platform such as Linux, windows and MAC OSX.

3. GTK# is part of the mono IDE.

Download MonoDevelop IDE from http://monodevelop.com/Download for mac and windows.

Simple Hello World program in GTK# MonoDevelop 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 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

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

Inter-Process Communication on Mac – Know How part1

Inter-process communication (IPC) can be defined as set of techniques used for  exchanging  data among multiple threads in one or more processes. Processes may be running on one or more computers connected by a network. IPC methods can divided into methods for message passing, synchronization, shared memory, and remote procedure calls (RPC).

Reasons for allowing two processes to communicate with each other may be different :

  • Information sharing
  • Computational speedup
  • Modularity
  • Convenience
  • Privilege separation

In this article we will discuss various techniques available on Mac to accomplish IPC. In the subsequent articles we will see the implementation part for various techniques.
Let’s look at the techniques available for IPC one by one. Read the rest of this entry

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

%d bloggers like this: