• Skip to main content
  • Skip to primary sidebar

Ravi Shankar

Tweaking Apps

  • Swift
  • Tech Tips

Objective C

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

Variables in Objective-C

June 26, 2013 By Ravi Shankar Leave a Comment

Objective-C also uses variables for storing data in memory like other programming languages. The variables are defined based on the type data type that will be stored. The general rule followed for naming variable are

  1. Use the camel case convention for variable i.e the first word in lowercase and second word in uppercase. For example if you are planning to store name of station in a variable then you can name it as “stationName”.
  2. You can also find out datatype of variable and name accordingly. For example, “strName” can tell the variable is of string data type and holds a name.
  3. Variables must contain only letters and numbers also it is better to avoid using underscore character.
  4. Be descriptive and avoid single letter or confusing words.

The variables are declared by first defining the datatype, followed by description of variable.

Declaring primitive datatypes

Examples :-

int count = 1;

float width = 23.34;

Declaring Objects

NSString *description;

NSArray *months;

The object variables are preceded with * before the description of variable.

Filed Under: Apple, Develop Tagged With: Apple, Objective C, Variables

NSLog datatype formatting option in Objective-C

March 4, 2013 By Ravi Shankar Leave a Comment

201303040743.jpg

NSLog in Objective-C is function call that is useful during debugging of a program. A typical NSLog example is

NSLog(@” How to use NSLog”);

The above statement prints the message ” How to use NSLog ” in console window. If you want to print the value of Objective-C variable or data type then you need to pass the relevant formatting parameter depending on data type. We have already seen different datatype and qualifiers in Objective-C, below is example Objective-C program with NSLog formatting option for each datatypes.

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])

{

int i = 5;

float f = 5.3;

double d = 66.76;

long int li = 22;

short int si = 12;

char c = ‘W’;

signed int sint = 34;

unsigned int uint = –23;

int o = 024;

int h = 0xAD;

long long ll = 45;

long double lf = 34.5;

unsigned long long ull = 12;

NSString *msg = @”NSLog Message”;

  

  

@autoreleasepool {

NSLog(@” print int %d”, i);

NSLog(@” print float %f”, f); // use %e for exponential

NSLog(@” print double %f”, d); // use %e for exponential

NSLog(@” print long int %li”, li);

NSLog(@” print short int %i”, si);

NSLog(@” print char %c”, c);

NSLog(@” print signed int %i”, sint);

NSLog(@” print unsigned int %u”, uint);

NSLog(@” print octal %o”, o);

NSLog(@” print hexadecimal %X”, h);

NSLog(@” print long long %lld”, ll);

NSLog(@” print long double %Lf”, lf);

NSLog(@” print unsigned long long %llu”, ull);

NSLog(@” print Object %@”, msg);

  

  

  

}

return 0;

}

The console output of the above Objective-C program is shown below

2013-03-04 07:25:10.187 NSLog Example[362:303] print int 5

2013-03-04 07:25:10.189 NSLog Example[362:303] print float 5.300000

2013-03-04 07:25:10.189 NSLog Example[362:303] print double 66.760000

2013-03-04 07:25:10.190 NSLog Example[362:303] print long int 22

2013-03-04 07:25:10.190 NSLog Example[362:303] print short int 12

2013-03-04 07:25:10.190 NSLog Example[362:303] print char W

2013-03-04 07:25:10.191 NSLog Example[362:303] print signed int 34

2013-03-04 07:25:10.191 NSLog Example[362:303] print unsigned int 4294967273

2013-03-04 07:25:10.192 NSLog Example[362:303] print octal 24

2013-03-04 07:25:10.192 NSLog Example[362:303] print hexadecimal AD

2013-03-04 07:25:10.193 NSLog Example[362:303] print long long 45

2013-03-04 07:25:10.193 NSLog Example[362:303] print long double 34.500000

2013-03-04 07:25:10.194 NSLog Example[362:303] print unsigned long long 12

2013-03-04 07:25:10.194 NSLog Example[362:303] print Object NSLog Message

int %d or %i

float %f or %e

double %f or %e

long int %li

short int %i

char %c

signed int %i

unsigned int %u

octal %o

hexa %X

long long %lld

long double %Lf

unsigned long long %llu

object %@

Filed Under: Apple, Develop, Programming Tagged With: Apple, data type, formatting option, NSLog, Objective C

Different data types in Objective-C

March 3, 2013 By Ravi Shankar Leave a Comment

Objective-C like any other programming languages has different data types like int, float, double, char and id. Data types are used for specifying the kind of data that is being stored in a variable. For example, the below code stores a single character to a variable “flag”

char flag = ‘1’

201303031336.jpg

Data type – char

The Objective-C Char data type can store single character of letter or number or special characters. This is done by enclosing the character with in single quotes.

var example1 = ‘W’ (store letter)   

var example2 = ‘3’ (store number)

var example3 = ‘:’ (store special character)

var example4 = ‘/n’ (backlash character is a special character)

Data type – int

int data type is used for storing positive or negative whole numbers. The range of values that can stored depends on the 32 bit or 64 bit operating system.

int count = 10

int exoctal = 036

int hex = 0xADD2

in the above example 0 preceding the number represents octal value and hex number is preceded with 0x

Date type – float & double

float is used for storing positive or negative decimal numbers.

float exfloat = 2.45

float exfloat2 = -0.345

float exfloat3 = 1.2e4

As shown in the last example, float data type can be represented in scientific notation 1.2e4 which is equivalent 1.2x10th power of 4.

double data type can store twice the range of float.

Data type – BOOL

BOOL is used for storing YES or NO i.e 1 or 0

BOOL flag = 1

Data type – id

id data type is used for storing object of any type.

id myfirstObject

Qualifiers

Qualifiers in Cbjective-C are used for increasing range of the data type and the range is system dependant. Qualifiers are placed just before the data type as shown below. The different qualifiers are long, long long, short, signed and unsigned.

Filed Under: Apple, Develop, iPhone, Programming Tagged With: Apple, data type, iphone, Objective C

‘NSInvalidUnarchiveOperationException’, reason: ‘Could not instantiate class named MKMapView’

February 1, 2013 By Ravi Shankar 2 Comments

Problem :- Xcode project with MapView control displays the error “‘NSInvalidUnarchiveOperationException’, reason: ‘Could not instantiate class named MKMapView'”

Solution :- The ‘Could not instantiate class named MKMapView’ error is displayed when the Xcode project with MapView control on xib does not include the MapKit library as part of the Link Libraries.

Select the Xcode project and navigate to Build Phases.

201302010703.jpg

Click the + sign under Link Binary with Libraries and select MapKit,framework from framework and libraries to add selection window.

201302010704.jpg

201302010705.jpg

Now running the project should not display the NSInvalidUnarchiveOperationException.

201302010709.jpg

Filed Under: Develop, Programming Tagged With: MapKit.framework, MKMapView, Objective C

Objective-C – What are Categories?

January 29, 2013 By Ravi Shankar Leave a Comment

Categories in Objective-C are used for adding extra functionality to a class without accessing the source code of the class and without subclassing it. Let us see this with an example by adding an additional method to NSNumber that just writes the value of the NSNumber argument to NSLog.

Create Project

Create a new Command Line Tool project for the example by providing the required details and selecting Type as Foundation.

201301282235.jpg

201301282236.jpg

Add Objective-C Category

Right click on the project, select New File then choose template for your new file as Objective-C category.

201301282251.jpg

Provide the name for your Category and select Category On as NSNumber (The class for which we are adding the additional method)

201301290550.jpg

Write Implementation

Two new files NSNumber+PrintNumber.h and NSNumber+PrintNumber.m files will be added to your project. Define the new method for NSNumber in the header file as shown below.

@interface NSNumber (PrintNumber)

-(void) printNumber: (NSNumber *) num;

@end

where printNumber is the new method that takes num of type NSNumber as the argument.

In the implementation file (NSNumber+PrintNumber.m ), add the code that write the value number to NSLog.

-(void) printNumber: (NSNumber *) num

{

NSLog(@” The number value is %@”, num);

}

Using Categories

Now in main.m file make a call to the new method of NSNumber after importing the “NSNumber+PrintNumber.h” as shown below.

#import <Foundation/Foundation.h>

#import “NSNumber+PrintNumber.h”

int main(int argc, const char * argv[])

{

@autoreleasepool {

  

// insert code here…

NSLog(@”Hello, World!”);

NSNumber *num = [[NSNumber alloc ] initWithInt:25];

[num printNumber:num];

}

return 0;

}

The call to [num printNumber:num] will write the value to the console.

201301290635.jpg

– Categories have access to instance variable of the original class but cannot have its own instance variable.

– Categories on parent class will be available for all its subclass as well.

– Using Categories you can override another method in the class.

–

Filed Under: Develop, Programming Tagged With: iOS, Objective C

Code Example – Check for Prime Number Objective C

February 10, 2012 By Ravi Shankar 1 Comment

This is a simple Objective C program written to check whether a number is a Prime number.

//

// main.m

// PrimeNumbers

//

// Created by Ravi Shankar on 10/02/12.

// Copyright (c) 2012 rshankar.com. All rights reserved.

//

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])

{

@autoreleasepool {

  

int number;

BOOL isPrime=YES;

NSLog (@”Enter a number”);

scanf(“%i”,&number);

for (int i=2; i < number –1; i++)

{

if (number % i == 0)

{

isPrime = NO;

break;

}

}

if (isPrime)

{

NSLog (@”%i is a Prime Number”,number);

}

else

{

   NSLog (@”%i is not a Prime Number”, number);

}

  

}

return 0;

}

Output (as displayed in Xcode console window)

2012-02-10 15:53:52.072 PrimeNumbers[1164:707] Enter a number

23

2012-02-10 15:53:58.665 PrimeNumbers[1164:707] 23 is a Prime Number


2012-02-10 15:54:41.469 PrimeNumbers[1176:707] Enter a number

24

2012-02-10 15:54:44.589 PrimeNumbers[1176:707] 24 is not a Prime Number


This program checks whether the number is divisible by any of the n-1 number and if divisible (% operator returns reminder as 0) then the flag is set to false otherwise it is set to true. Then based on the flag value the message is printed to the console window.


Filed Under: Blogging, Develop, ios Tagged With: Objective C, prime number, Program

Dissecting Objective-C program

January 14, 2012 By Ravi Shankar Leave a Comment

Fotolia_29238788_XS.jpg

We have already seen couple of examples in Objective-C like writing your first program in Objective-C and adding Objective-C classes. Now let us try and analyze the code to learn basic coding on Objective-C program.

Adding Comments

The very basic thing to learn is any programming language is “how to add comments”. In Objective-C you can add comments by adding two consecutive slashes “//” before the text entries. And if you want to add block of comments (more than one line) then you start with /* and end the comment with */

Including Header files

In Objective-C, users can include header files by adding “#import <header filename>”. This would include functions and classes from the header files in to the current program. The examples that has been discussed includes “Foundation” and “Calci” header files.

#import <Foundation/Foundation.h>

#import “Calci.h”

main keyword

int main (int argc, const char * argv[])

“main” is the keyword that marks the beginning line for execution of the program.

Reserving memory

  @autoreleasepool {

The execution code is provided within autoreleasepool and this allocates memory for the program. Now you do not have to explicitly drain the pool, the latest release will automatically drain the allocated memory.

Printing Message

 

  NSLog(@”My First Objective C Program using Xcode!”);

 

NSLog routine is used for printing text messages to the console. The text that needs to be printed is preceded with “@” character. And if you want to print value from a variable then you can use “%i” along with text.

 

NSLog(@”Addition of two numbers %i”, [calculator addition]);

 

Method definition

 

In Objective-C, you can define methods as shown below

 

-(void) setNumber1:(int) n1

-(int) addition

  • “-” refers to the access specifier.
  • void and int specifies the return type for the method.
  • setNumber1 and addition refers to the method name.
  • (int) n1 specifies the type of argument and argument that will be passed to the method.
  • return number1+number2; – “return” keyword is used returning the value from the method.

Filed Under: Apple, Develop, ios Tagged With: Apple, Objective C, Program

  1. Pages:
  2. 1
  3. 2
  4. »
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