• Skip to main content
  • Skip to primary sidebar

Ravi Shankar

Tweaking Apps

  • Swift
  • Tech Tips

Develop

Selection Sort

July 1, 2014 By Ravi Shankar Leave a Comment

Selection Sort algorithm does the same amount of comparison( N*(N-1)/2 ) like bubble sort but the number swaps (N) is reduced drastically. This sort algorithm traverse through all the items, picks the smallest number and swaps it with left most item. Then the step is repeated for the next smallest number until it reaches the end of the elements in array. Listed below is the code for Selection Sort and screenshot of this algorithm executed in Playground.

import UIKit

func swapNumbers(index1 :Int,index2: Int) {

let temp = inputArr[index1]

inputArr[index1] = inputArr[index2]

inputArr[index2] = temp

}


var inputArr = Int[]()


// generate random numbers

for rIndex in 0..10 {

inputArr.append(((Int(arc4random()) % 100)))

}


inputArr


var minIndex: Int = 0


func selectionSort(inputArray :Int[]) {

for var index:Int = 0; index < inputArr.count-1; ++index {

minIndex = index

for (var jIndex: Int = index + 1; jIndex < inputArr.count-1; ++jIndex) {

if inputArr[jIndex] < inputArr[minIndex] {

minIndex = jIndex

}

}

swapNumbers(index, minIndex)

}

}


selectionSort(inputArr)


inputArr

  1. swapNumber function is used for swapping the numbers in the array for the given indexes.
  2. The numbers for the input array is randomly generated using the arc4random function.
  3. selectionSort function is the selectionSort algorithm that starts from the first number in the array and compares it with other elements and finds smallest one (stores the index as minIndex).
  4. Then swaps the smallest number with the left most and repeats these steps for the next number in the array until it reaches end of array.


Selection Sort algorithm in Swift

Filed Under: Develop, ios, Xcode Tagged With: algorithm, Selection Sort, Swift, Xcode

Binary search

June 26, 2014 By Ravi Shankar Leave a Comment

After a simple bubble sort algorithm (not the most efficient sorting algorithm), let us try to implement Binary search in Swift Programming Language. Binary search algorithm can be applied only on sorted arrays. So let us first generate random numbers and store them in an array. Then call the bubble sort function to sort the numbers by passing the array to the function.

import Cocoa


func swapNumbers(index1 :Int,index2: Int) {

let temp = inputArr[index1]

inputArr[index1] = inputArr[index2]

inputArr[index2] = temp

}


func bubbleSort(inputArray :Int[]) {

for var index: Int = inputArr.count-1; index > 1; --index {

for var jIndex: Int = 0; jIndex < index; ++jIndex {

if inputArr[jIndex] > inputArr[jIndex + 1] {

swapNumbers(jIndex, jIndex+1)

}

}

}

}


var inputArr = Int[]()


// generate random numbers

for rIndex in 0..10 {

inputArr.append(((Int(arc4random()) % 100)))

}


//call bubblesort function to sort the numbers in array

bubbleSort(inputArr)


inputArr

Steps for Binary search algorithm

  • Set lower index to 0 and upper index to total count of elements
  • Set the current index to the median of lower and upper index
  • Repeat these checks in a infinite while loop.
  • Check if passed number is equal to number returned by current index. If it matches then return the current index.
  • If the lower index is greater than upper index, it means the search item does not exist in the array. Hence return the array’s total elements.
  • If current index is greater than the search item then decrease the upper index
  • if current index is less than the search item then increase the lower index.

func findItem(searchItem :Int) -> Int{

var lowerIndex = 0;

var upperIndex = inputArr.count - 1


while (true) {

var currentIndex = (lowerIndex + upperIndex)/2

if(inputArr[currentIndex] == searchItem) {

return currentIndex

} else if (lowerIndex > upperIndex) {

return inputArr.count

} else {

if (inputArr[currentIndex] > searchItem) {

upperIndex = currentIndex - 1

} else {

lowerIndex = currentIndex + 1

}

}

}

}


findItem(78)

Filed Under: Apple, Develop, ios, Programming, Xcode Tagged With: Apple, binary search, bubble sort, Swift, Xcode

Basic overview of Xcode

June 21, 2014 By Ravi Shankar Leave a Comment

Xcode is the primary tool used for the development of Mac and iOS applications. This is a free tool which can be downloaded from developer.apple.com website. You can use Xcode for Writing code, Building, Testing (Unit test) and for Distribution (Submitting to App Store).

Xcode Window

Different Panes in Xcode

Navigator

 

This is available at the left hand side of Xcode window. Provides option to navigate through the project files, Issues, Debug Session, Breakpoints etc.

Xcode Navigator Pane

Utilities

 

This is available at the right hand side of Xcode window. This contains File inspector, Quick Help inspector, File Template Library, Code Snippet Library, Object library and Media library. These tools help the developer with designing the user interface and writing coding using Xcode.

Xcode Utilities Pane

Editor

This available at the Centre of Xcode window and used for writing your code.

Xcode Editor Window

Interface builder

Interface builder or IB is available at the Centre of Xcode window when you navigate to your .xib file or storyboard. This allows users to build UI for their app.

Xcode Interface Builder

Debug and Console

 

Debug and Console panes are available at the bottom of Xcode window. As the name suggests Debug provides option for debugging your app and console displays both system, exceptions and app written messages.

Xcode Debug and Console Windows

Toolbar

Xcode Toolbar

The Toolbar provides the option to Run, Analyse, Build and Test your App. This is the place where you would specify whether you want to run the app in simulator (iPhone or iPad) or real device,

Xcode Choose Simulator

Another important feature of Toolbar is the option it provides to show or hide panes of Xcode.

Xcode Show or Hide Pane

The Editor option provides toggle option to show or hide Standard Editor, Assistant Editor and Version Editor. Similarly View option provide option to show or hide Navigator, Debug Area and Utilities. You can also launch Organizer from Xcode Toolbar.

Oragnizer

This provides access to the Documentation, Projects, Archives, Repositories and Devices (Provisioning Profiles)

Xcode Organizer

Filed Under: Develop, Xcode Tagged With: iOS, iOS Simulator

Decode job advert posted in Swift Language

March 20, 2014 By Ravi Shankar 1 Comment

I came across this unique Swift job advert in stackoverflow.com posted by Criteo. (Need to add override for the init function, missed in the original job post)

var hello = "Hello, I am a Swift Program, paste me in the playground"

var doyouswift = "You think you have what it takes to build the next mobile advertising technologies ?"

class Hire {

    var r = "&"

    var d = "r"

    var ec = "@rt"

    func email() -> String{

        return "look at gogogo's"

    }

}

class HireMe: Hire{

    var me = "[email protected]"

    var crit = "e"

    let o = ".com"

  override init() {

        super.init()

        ec = "ruit"

    }

override func email() -> String{

        return super.email()+" preview, remove quotes and braces to reveal the email."

    }

}

var gogogo = HireMe()

println(gogogo.email())


Filed Under: Apple, Develop, Programming Tagged With: Apple, Job, Swift

Simple UITableView and UIAlertView example

January 9, 2014 By Ravi Shankar 1 Comment

In this article, we are going to see how to create a simple UITableView for displaying data. And display an alert on selection of any row using UIAlertView.

Launch Xcode, Click File > New Project and select Single View Application as the project template.

Choose a template for new new project

Enter the project details for Product Name, Organization Name, Company Identifier and Target device as iPhone.

201401091129.jpg

Then choose a location on your Mac to save the project.

201401091131.jpg

Navigate to Main.Storyboard and and delete the ViewController under View Controller Scene. Since we want a TableView, we are going to replace this View Controller with UITableViewController.

201401091134.jpg

Note :- We could have also used UITableView on top of View Controller but we will keep that for another session.

Now select UITableViewController from the Object library, drag and drop it on to the User Interface.

201401091141.jpg

Let us see the how to display list of values in the above table.

Navigate to ViewController.h in the Project Navigator and replace the following line

@interface ViewController : UIViewController

with

@interface ViewController : UITableViewController

Then use the Identity Inspector and specify the class for TableViewController as ViewController.

201401091146.jpg

Edit ViewController.m file and add a new instance variable and populate the cities in ViewDidLoad method.

@implementation ViewController

{

NSArray *cities;

}

– (void)viewDidLoad

{

[super viewDidLoad];

  

//Create the list of cities that will be displayed in the tableview

  

cities = [[NSArray alloc] initWithObjects:@”Chennai”,@”Mumbai”,@”New Delhi”, @”New York”, @”London”,@”Tokyo”,@”Stockholm”,@”Copenhagen”,@”Manchester”,@”Paris”,nil];

}

In the above code, cities is of type NSArray and it is initialised with set of values in the ViewDIdLoad method. These values will be displayed in the UITableView.

The ViewController will act as a delegate and datasource for the UITableViewController. These connections are automatically created and you can verify them by right clicking on the ViewController. If we had used UITableView instead of UITableViewController then these connections have to be made manually.

201401091202.jpg

The data for the tableview is provided by the following methods and these methods needs to be implemented in ViewController.m.

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

numberOfRowsInSection method is used for specifying the total rows in each section for the tableview. In this example, the UITableView has only one section for displaying the cities.

cellForRowAtIndexPath method is used for providing the data to each row in the TableView. The data is populated using the indexPath for each row.

Copy the method implementation to ViewController.m file

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

return [cities count];

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@”Cities”];

  

cell.textLabel.text = [cities objectAtIndex:indexPath.row];

  

return cell;

}

The numberOfRowsInSection provides the tableview with the total count of rows i.e number of items in the cities array object. In the cellForRowAtIndexPath, we create a reusable UITableViewCell and assign the cities as per the row indexPath. Also make sure to specify the Identifier for prototype cell (User Interface) as Cities using the Attributes Inspector.

Now if you build and run the project, you should see a table with list of cities as shown below.

201401091307.jpg

Display the row selection using UIAlertView

Nothing will happen when you select any of the rows in the above table. Let us use the UIAlertView to display the row selection and for this we need to implement didSelectRowAtIndexPath in ViewController.m. Add the following didSelectRowAtIndexPath method implementation to the file.

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

NSString *cityName = [cities objectAtIndex:indexPath.row];

  

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@”City” message:cityName delegate:self cancelButtonTitle:@”Cancel” otherButtonTitles:nil, nil];

  

[alertView show];

}

The above code first retrieves the city name from cities array object using the row’s indexPath. In the second line, we create a instance of UIAlertView with title as “City”, selected city for the message attribute and provide the title for the cancel button. The delegate for UIAlertView will be ViewController and this specified by the delegate attribute. In the last line we use the show method to display the alert.

UITableView showing UIAlertView

Download the source code from here.

Filed Under: Develop, ios, iPhone, Programming, Xcode Tagged With: iOS, iphone, UIAlertView, UITableView, Xcode

How to change page scaling in Xcode

August 15, 2013 By Ravi Shankar Leave a Comment

Xcode provides option to increase or decrease the page scaling. This page scaling option is available as part of the Page Setup. This feature is quite useful when you want reduce the number of pages used for printing any Objective-C code.

201308152115.jpg

The default page scale is set to 100% and you can change this by following the below mentioned steps.

Click File menu and select Page Setup from the menu list.

201308152110.jpg

This should display the following Page Setup screen.

201308152112.jpg

Navigate to the Scale option and change the default value from 100% to say 50%. Then click OK button to confirm and save the changes. Now when you go to print preview screen (Xcode File menu -> Print), you should notice the effect of reduced Scale changes.

201308152118.jpg

Filed Under: Apple, Develop, ios, Xcode Tagged With: Apple, page scale, page setup, Print, Xcode

What is Delegation in iOS ?

August 15, 2013 By Ravi Shankar Leave a Comment

Delegation is one of the commonly used pattern in iOS. This is used tell an object to act on behalf of another. Refer to Apple documentation for detailed information on delegate pattern. Let us see this with an example program that uses UITextFieldDelegate.

This is a SingleView Project with one UITextField control.

#import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad

{

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

UITextField *tfMessage1= [[UITextField alloc] initWithFrame:CGRectMake(50, 80, 250, 150)];

tfMessage1.borderStyle = UITextBorderStyleRoundedRect;

[self.view addSubview:tfMessage1];

}

– (void)didReceiveMemoryWarning

{

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

@end

Now if you run the project using Xcode simulator, the UITextView will be displayed. You can type in the UITextField but when pressing Return on the keyboard will do nothing. By using delegate pattern we are going to tell UIViewController to process the pressing of the return button on behalf of UITextField and hide the keyboard.

Step 1: Open the ViewController.h file and implement the UITextViewDelegate as shown below.

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITextFieldDelegate>

@end

Step 2: Navigate to viewDidLoad method in implementation file, add “self.tfMessage1.delegate= self” as shown in the below code snippet.

– (void)viewDidLoad

{

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

UITextField *tfMessage1= [[UITextField alloc] initWithFrame:CGRectMake(50, 80, 250, 150)];

tfMessage1.borderStyle = UITextBorderStyleRoundedRect;

[self.view addSubview:tfMessage1];

tfMessage1.delegate = self;

}

This makes the UIViewController to act on behalf of UITextField.

Step 3: Now implement the following method that would process the “Pressing of return” key.

-(BOOL)textFieldShouldReturn:(UITextField *)textField

{

[textField setUserInteractionEnabled:YES];

[textField resignFirstResponder];

return YES;

}

Filed Under: Apple, Develop, ios Tagged With: Apple, delegate pattern, delegation, Objective C

Different ways to connect IBAction to UIButton

August 13, 2013 By Ravi Shankar 2 Comments

In this tutorial, we are going to see the different ways for connecting IBAction to UIButton. Let see this with an example that displays an alert message on the touch event of UiButton.

Method 1 (Assistant Editor):

Step 1: Drag and drop Round Rect Button from the Objects library on to Interface builder.

Step 2: Now click the Show Assistant Editor option on Xcode toolbar. This should display the Interface builder and code editor adjacent to each other as shown below.
201308130927.jpg
Step 3: Select the button on Interface builder then hold control key on keyboard and drag the line to the editor window (.h file).

201308130937.jpg
You should notice Insert Outlet, Action or Outlet Collection entry as shown in the above screenshot. Selecting the option would display a window for defining the IBAction.
201308130943.jpg
Step 4: Select “Action” for Connection, provide a name (e.g.:- showAlert), Event as “Touch Up Inside” then click Connect. This should add a new IBAction entry in the header and implementation file.

Header file (.h)
201308130949.jpg
Implementation File (.m)
201308130951.jpg
Step 5 : Now add the following UIAlertView code inside the showAlert method in implementation file.

  UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@”Demo” message:@”IBAction Demo” delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];

  [alertView show];

201308130953.jpg

Executing the project in the simulator should display the following alert on tapping the Button.

201308130956.jpg

Method 2 (Connections Inspector) :

Step 1: Drag and drop a Round Rect Button on to the Interface builder.

Step 2: Navigate to implementation file and add the following IBAction code for displaying the Alert.

201308131002.jpg

Step 3: Open nib file, navigate to Show Connections Inspector option available on the left hand side.

201308131000.jpg

Selecting the File Owner’s option should display the details in the Connections Inspector. This should display the IBAction method under the Received Actions section.

201308131006.jpg

Step 4: select showAlert and drag it to the UIButton on the Interface builder.

201308131009.jpg

Releasing the mouse click should display the following Events list. Select Touch Up Inside from the list.

201308131011.jpg

Once connected, you should see the connection between the IBAction method and the control under Received Actions.

201308131012.jpg

Method 3 (Programmatically):

Step 1: Launch the implementation file for adding the Round Rect Button Programmatically.

Step 2: Add the IBAction showAlert method with the following alert message.

  UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@”Demo” message:@”IBAction Demo” delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];

  [alertView show];

201308131002.jpg

Step 3: Navigate to ViewDidLoad Method and add the following code to instantiate UI button and connect button to Touch Up Inside event with showAlert method.

– (void)viewDidLoad

{

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

  

UIButton *btnDemo = [UIButton buttonWithType:UIButtonTypeRoundedRect]; // Create Round Rect Type button.

btnDemo.frame = CGRectMake(100, 100, 100, 100); // define position and width and height for the button.

[btnDemo setTitle:@”Show Alert” forState:UIControlStateNormal];

  

//connect the showAlert method with button target attribue. Also spectify when (event) you want to call

//this methid

[btnDemo addTarget:self action:@selector(showAlert:) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:btnDemo];

}

Filed Under: Apple, Develop, ios Tagged With: Apple, IBAction, UIButton

  1. Pages:
  2. «
  3. 1
  4. 2
  5. 3
  6. 4
  7. 5
  8. »
« Previous Page
Next Page »

Primary Sidebar

TwitterLinkedin

Recent Posts

  • How to block keywords in Jio broadband
  • How to disable opening an app automatically at login in Mac
  • How to set preferred Wifi network on Mac
  • Attribute Unavailable: Estimated section warning before iOS 11.0
  • How to recover Firefox password from Time Machine backup

Pages

  • About
  • Privacy Policy
  • Terms and Conditions

Copyright 2022 © rshankar.com

Terms and Conditions - Privacy Policy