Objective-C Flashcards

1
Q

Objective-C Overview

A
  • developed on top of C
  • Small Talk features added to make it object-oriented
  • initially developed by NeXT for its NeXTSTEP OS and taken over by Apple for its iOS and MacOS
  • GCC compiler
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Objective-C Object Oriented

A
  • encapsulation
  • data hiding
  • inheritance
  • polymorphism
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Objective-C Foundation Framework

A
  • extended data types like NSArray, NSDictionary, NSSET
  • file, string functions
  • URL handling, data formatting, data handling, error handling
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Objective-C Program Structure

A
  • preprocessor commands
  • interface
  • implementation
  • method
  • variables
  • statements and expressions
  • comments
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Objective-C Hello World program

A

import

@interface SampleClass:NSObject
- (void)sampleMethod;
@end

@implementation SampleClass

  • (void)sampleMethod {
    NSLog(@”Hello, World! \n”);
    }

@end

int main() {
   /* my first program in Objective-C */
   SampleClass *sampleClass = [[SampleClass alloc]init];
   [sampleClass sampleMethod];
   return 0;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Objective-C Tokens

A

a token is either a keyword, an identifier, a constant, a string literal, or a symbol

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Objective-C Semicolons

A

statement terminator

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Objective-C Comments

A
  • ignored by the compiler

- start with /* and terminate with */

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Objective-C Identifier

A
  • name used to identify a variable, function or any other user-defined item
  • starts with a letter or an underscore followed by zero or more letters, underscores and digits
  • case-sensitive
  • punctuation characters such as @, $ and % are not allowed
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Objective-C Reserved Words

A
auto	
else	
long	
switch
break	
enum	
register	
typedef
case	
extern	
return	
union
char	
loat	
short	
unsigned
const	
for	
signed	
void
continue	
goto	
sizeof	
volatile
default	
if	
static	
while
do	
int	
struct	
_Packed
double	
protocol	
interface	
implementation
NSObject	
NSInteger	
NSNumber	
CGFloat
property	
nonatomic;	
retain	
strong
weak	
unsafe_unretained;	
readwrite	
readonly
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Objective-C Whitespace

A

totally ignored

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Objective-C Data Types

A
  • basic types
  • -integer
  • -floating point
  • enumerated types
  • -used to define variables that can only be assigned
  • -certain discrete integer values
  • void type
  • -no value is available
  • derived types
  • -pointer
  • -array
  • -structure
  • -union
  • -function
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Objective-C Integer Types

A

char
1 byte
-128 to 127 or 0 to 255

unsigned char
1 byte
0 to 255

signed char
1 byte
-128 to 127

int
2 or 4 bytes
-32,768 to 32,767 or -2,147,483,648 to 2,147,483,647

unsigned int
2 or 4 bytes
0 to 65,535 or 0 to 4,294,967,295

short
2 bytes
-32,768 to 32,767

unsigned
short
2 bytes 0 to 65,535

long
4 bytes
-2,147,483,648 to 2,147,483,647

unsigned long
4 bytes
0 to 4,294,967,295

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Objective-C Floating-Point Types

A

float
4 byte
1.2E-38 to 3.4E+38
6 decimal places

double
8 byte
2.3E-308 to 1.7E+308
15 decimal places

long double
10 byte
3.4E-4932 to 1.1E+4932
19 decimal places

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Objective-C void type

A

no value is available

-function returns as void
void exit(Int status);
-function arguments as void
int rand(void);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Objective-C Variables

A
  • name given to a storage area
  • name can be composed of letters, digits and the underscore.
  • name must begin with either a letter or underscore
  • char
  • -typically one byte
  • -integer type

-Int

  • float
  • -single-precision floating point value
  • double
  • -double precision floating point value
  • void
  • -represents the absence of type
  • other types
  • -enumeration, pointer, array, structure, union

int i, j, k;
char c, ch;
float f, salary;
double d;

variables can be initialized in their declaration:
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = ‘x’; // the variable x has the value ‘x’.

variable declaration provides assurance to the compiler that there is one variable existing with the given type and name. Uses the keyword extern.
extern int a, b;
extern int c;
extern float f;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Objective-C Lvalues and Rvalues

A
  • lvalue
  • -expression that refers to a memory location
  • -may appear as either the left-hand or right-hand side of an assignment
  • -variables are lvalues
  • rvalue
  • -data value that is stored at some address in memory
  • -expression that cannot have a value assigned to it which means that an rvalue may appear on the right-hand but not the left-hand side of an assignment
  • -numeric literals are rvalues
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Objective-C Constants

A
  • fixed values that may not be altered during program execution
  • also called literals
  • type can be integer, floating, character, string or enumeration
  • integer literal can be a decimal, octal or hexadecimal constant
  • floating point literals have an integer part, decimal part, fractional part and exponent part
  • character constants are enclosed in single quotes
  • string literals are enclosed in double quotes
  • constants can be defined
  • -using #define preprocessor
  • -using const keyword
#define LENGTH 10   
#define WIDTH  5
#define NEWLINE '\n'

const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = ‘\n’;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Objective-C Operators

A
-arithmetic
\+
-
*
/
%
\++
--
-relational
==
!=
>
<
>=
<=

-logical
&&
||
|

-bitwise
&amp;
|
^
~
<<
>>
-assignment
=
\+=
-=
*=
/=
%=
<<=
>>=
&amp;=
^=
|=

-misc

sizeof()
–returns the size of a variable

&
–returns the address of a variable

*
–pointer to a variable

?:
--conditional expression
if condition is true ?
then value x:
otherwise value y
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Objective-C Loops

A

while loop

for loop

do..while loop

nested loops

loop control statements:

  • -break statement terminates loop
  • -continue statement skips remainder of body
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Objective-C Functions/Methods

A
  • group of statements that perform a task
  • every program has a main() function
  • has declaration and definition
/* function returning the max between two numbers */
- (int) max:(int) num1 secondNumber:(int) num2 {
   /* local variable declaration */
   int result;
   if (num1 > num2) {
      result = num1;
   } else {
      result = num2;
   }

return result;
}

  • arguments
  • -call by value (used by default)
  • -call by reference
22
Q

Objective-C Blocks

A

-object that combines data with related behavior

void (^simpleBlock)(void) = ^{
NSLog(@”This is a block”);
};

invoked by:
simpleBlock();

  • can take arguments and return values
  • can use type definitions
23
Q

Objective-C Numbers

A

NSNumber methods

+ (NSNumber *)numberWithBool:(BOOL)value
Creates and returns an NSNumber object containing a given value, treating it as a BOOL.

+ (NSNumber *)numberWithChar:(char)value
Creates and returns an NSNumber object containing a given value, treating it as a signed char.

+ (NSNumber *)numberWithDouble:(double)value
Creates and returns an NSNumber object containing a given value, treating it as a double.

+ (NSNumber *)numberWithFloat:(float)value
Creates and returns an NSNumber object containing a given value, treating it as a float.

+ (NSNumber *)numberWithInt:(int)value
Creates and returns an NSNumber object containing a given value, treating it as a signed int.

+ (NSNumber *)numberWithInteger:(NSInteger)value
Creates and returns an NSNumber object containing a given value, treating it as an NSInteger.

  • (BOOL)boolValue
    Returns the receiver’s value as a BOOL.
  • (char)charValue
    Returns the receiver’s value as a char.
  • (double)doubleValue
    Returns the receiver’s value as a double.
  • (float)floatValue
    Returns the receiver’s value as a float.
  • (NSInteger)integerValue
    Returns the receiver’s value as an NSInteger.
  • (int)intValue
    Returns the receiver’s value as an int.
  • (NSString *)stringValue
    Returns the receiver’s value as a human-readable string.
24
Q

Objective-C Decision Making Statements

A

if statement

if…else statement

nested if statement

switch statement

nested switch statement

25
Q

Objective-C Arrays

A

-store fixed-size sequential collection of elements of the same type

double balance[10];
double balance[10];

  • accessed with index
  • can have multidimensional arrays
  • can pass arrays to functions
  • can return an array from a function
  • ca generate a pointer to the first element of an array
26
Q

Objective-C Pointers

A

-variable whose value is the address of another variable

int ip; / pointer to an integer */
double dp; / pointer to a double */
float fp; / pointer to a float */
char ch / pointer to a character */

int main () {
   int  var = 20;    /* actual variable declaration */
   int  *ip;         /* pointer variable declaration */  
   ip = &amp;var;       /* store address of var in pointer variable*/

NSLog(@”Address of var variable: %x\n”, &var );

   /* address stored in pointer variable */
   NSLog(@"Address stored in ip variable: %x\n", ip );
   /* access the value using the pointer */
   NSLog(@"Value of *ip variable: %d\n", *ip );

return 0;
}

  • assign a NULL value to a pointer
  • pointer arithmetic
  • array of pointers
  • pointer to pointer
  • pass pointers to functions
  • return pointer from functions
27
Q

Objective-C Strings

A

-represented using NSString and its subclass NSMutableString

int main () {
NSString *greeting = @”Hello”;
NSLog(@”Greeting message: %@\n”, greeting );

return 0;
}

  • (NSString *)capitalizedString;
    Returns a capitalized representation of the receiver.
  • (unichar)characterAtIndex:(NSUInteger)index;
    Returns the character at a given array position.
  • (double)doubleValue;
    Returns the floating-point value of the receiver’s text as a double.
  • (float)floatValue;
    Returns the floating-point value of the receiver’s text as a float.
  • (BOOL)hasPrefix:(NSString *)aString;
    Returns a Boolean value that indicates whether a given string matches the beginning characters of the receiver.
  • (BOOL)hasSuffix:(NSString *)aString;
    Returns a Boolean value that indicates whether a given string matches the ending characters of the receiver.
  • (id)initWithFormat:(NSString *)format …;
    Returns an NSString object initialized by using a given format string as a template into which the remaining argument values are substituted.
  • (NSInteger)integerValue;
    Returns the NSInteger value of the receiver’s text.
  • (BOOL)isEqualToString:(NSString *)aString;
    Returns a Boolean value that indicates whether a given string is equal to the receiver using a literal Unicode-based comparison.
  • (NSUInteger)length;
    Returns the number of Unicode characters in the receiver.
  • (NSString *)lowercaseString;
    Returns lowercased representation of the receiver.
  • (NSRange)rangeOfString:(NSString *)aString;
    Finds and returns the range of the first occurrence of a given string within the receiver.
  • (NSString *)stringByAppendingFormat:(NSString *)format …;
    Returns a string made by appending to the receiver a string constructed from a given format string and the following arguments.
  • (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set;
    Returns a new string made by removing from both ends of the receiver characters contained in a given character set.
  • (NSString *)substringFromIndex:(NSUInteger)anIndex;
    Returns a new string containing the characters of the receiver from the one at a given index to the end.
28
Q

Objective-C Structures

A

-user-defined data type which allows combining data types of different kinds

struct Books {
   NSString *title;
   NSString *author;
   NSString *subject;
   int   book_id;
} book;
int main() {
   struct Books Book1;        /* Declare Book1 of type Book */
   struct Books Book2;        /* Declare Book2 of type Book */

/* book 1 specification */
Book1.title = @”Objective-C Programming”;
Book1.author = @”Nuha Ali”;
Book1.subject = @”Objective-C Programming Tutorial”;
Book1.book_id = 6495407;

   /* book 2 specification */
   Book2.title = @"Telecom Billing";
   Book2.author = @"Zara Ali";
   Book2.subject = @"Telecom Billing Tutorial";
   Book2.book_id = 6495700;

/* print Book1 info */
NSLog(@”Book 1 title : %@\n”, Book1.title);
NSLog(@”Book 1 author : %@\n”, Book1.author);
NSLog(@”Book 1 subject : %@\n”, Book1.subject);
NSLog(@”Book 1 book_id : %d\n”, Book1.book_id);

/* print Book2 info */
NSLog(@”Book 2 title : %@\n”, Book2.title);
NSLog(@”Book 2 author : %@\n”, Book2.author);
NSLog(@”Book 2 subject : %@\n”, Book2.subject);
NSLog(@”Book 2 book_id : %d\n”, Book2.book_id);

return 0;
}

  • can be passed as function arguments
  • can define pointers to structures
-can pack data in a structure
struct packed_struct {
   unsigned int f1:1;
   unsigned int f2:1;
   unsigned int f3:1;
   unsigned int f4:1;
   unsigned int type:4;
   unsigned int my_int:9;
} pack;
29
Q

Objective-C Preprocessors

A
  • not part of the compiler
  • separate step in the compilation process
  • text substitution tool that instructs the compiler to do required preprocessing before actual compilation
#define
Substitutes a preprocessor macro
#include
Inserts a particular header from another file
#undef
Undefines a preprocessor macro
#ifdef
Returns true if this macro is defined
#ifndef
Returns true if this macro is not defined
#if
Tests if a compile time condition is true
#else
The alternative for #if
#elif
#else an #if in one statement
#endif
Ends preprocessor conditional
#error
Prints error message on stderr
#pragma
Issues special commands to the compiler using a standardized method
30
Q

Objective-C Predefined Macros

A

__DATE__
The current date as a character literal in “MMM DD YYYY” format

__TIME__
The current time as a character literal in “HH:MM:SS” format

__FILE__
This contains the current filename as a string literal.

__LINE__
This contains the current line number as a decimal constant.

__STDC__
Defined as 1 when the compiler complies with the ANSI standard.

31
Q

Objective-C Preprocessor Operators

A

\
macro continuation

# 
stringize
##
token pasting

defined()

32
Q

Objective-C Typedef

A

-can be used to give a type a new name

typedef unsigned char BYTE;
BYTE b1, b2;

typedef struct Books {
   NSString *title;
   NSString *author;
   NSString *subject;
   int book_id;
} Book;

int main() {
Book book;
book.title = @”Objective-C Programming”;
book.author = @”TutorialsPoint”;
book.subject = @”Programming tutorial”;
book.book_id = 100;

NSLog( @”Book title : %@\n”, book.title);
NSLog( @”Book author : %@\n”, book.author);
NSLog( @”Book subject : %@\n”, book.subject);
NSLog( @”Book Id : %d\n”, book.book_id);

return 0;
}

33
Q

Objective-C Type Casting

A

-convert a variable from one data type to another data type

int main() {
   int sum = 17, count = 5;
   CGFloat mean;

mean = (CGFloat) sum / count;
NSLog(@”Value of mean : %f\n”, mean );

return 0;
}

34
Q

Objective-C Integer Promotion

A

-process by which values of integer type “smaller” than Int or unsigned int are converted to Int or unsigned int

int main() {
   int  i = 17;
   char c = 'c';  /* ascii value is 99 */
   int sum;

sum = i + c;
NSLog(@”Value of sum : %d\n”, sum );

return 0;
}

35
Q

Objective-C Log Handling

A

NSLog

int main() {
   NSLog(@"Hello, World! \n");
   return 0;
}
36
Q

Objective-C Error Handling

A

NSError

-consists of Domain, Code and User Info

NSString *domain = @”com.MyCompany.MyApplication.ErrorDomain”;
NSString *desc = NSLocalizedString(@”Unable to complete the process”, @””);
NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : desc };
NSError *error = [NSError errorWithDomain:domain code:-101 userInfo:userInfo];

37
Q

Objective-C Command-Line Arguments

A

-can pass some values from the command line to an Objective-C program

int main( int argc, char *argv[] ) {
if( argc == 2 ) {
NSLog(@”The argument supplied is %s\n”, argv[1]);
} else if( argc > 2 ) {
NSLog(@”Too many arguments supplied.\n”);
} else {
NSLog(@”One argument expected.\n”);
}
}

38
Q

Objective-C Classes & Objects

A
  • The class is defined in two different sections namely @interface and @implementation.
  • Almost everything is in form of objects.
  • Objects receive messages and objects are often referred as receivers.
  • Objects contain instance variables.
  • Objects and instance variables have scope.
  • Classes hide an object’s implementation.
  • Properties are used to provide access to class instance variables in other classes.
class definition:
@interface Box:NSObject {
   //Instance variables
   double length;    // Length of a box
   double breadth;   // Breadth of a box
}
@property(nonatomic, readwrite) double height;  // Property

@end

class creation and allocation:
Box box1 = [[Box alloc]init];     // Create box1 object of type Box
Box box2 = [[Box alloc]init];     // Create box2 object of type Box
accessing class members:
@interface Box:NSObject {
   double length;    // Length of a box
   double breadth;   // Breadth of a box
   double height;    // Height of a box
}

@property(nonatomic, readwrite) double height; // Property
-(double) volume;
@end

@implementation Box

@synthesize height;

-(id)init {
   self = [super init];
   length = 1.0;
   breadth = 1.0;
   return self;
}

-(double) volume {
return lengthbreadthheight;
}

@end

int main() {
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];    
   Box *box1 = [[Box alloc]init];    // Create box1 object of type Box
   Box *box2 = [[Box alloc]init];    // Create box2 object of type Box

double volume = 0.0; // Store the volume of a box here

   // box 1 specification
   box1.height = 5.0; 
   // box 2 specification
   box2.height = 10.0;

// volume of box 1
volume = [box1 volume];
NSLog(@”Volume of Box1 : %f”, volume);

// volume of box 2
volume = [box2 volume];
NSLog(@”Volume of Box2 : %f”, volume);

[pool drain];
return 0;
}

39
Q

Objective-C Properties

A
  • ensure that the instance variable of the class can be accessed outside the class
  • begin with @property keyword
  • followed by access specifiers
  • followed by data type of the variable
  • property name terminated by a semicolon
  • can add synthesize statement, but it’s taken care of by XCode
40
Q

Objective-C Inheritance

A

-can define a class in terms of another class

  • base class
  • -existing class
  • derived class
  • -new class

@interface Person : NSObject {
NSString *personName;
NSInteger personAge;
}

  • (id)initWithName:(NSString *)name andAge:(NSInteger)age;
  • (void)print;

@end

@implementation Person

- (id)initWithName:(NSString *)name andAge:(NSInteger)age {
   personName = name;
   personAge = age;
   return self;
}
  • (void)print {
    NSLog(@”Name: %@”, personName);
    NSLog(@”Age: %ld”, personAge);
    }

@end

@interface Employee : Person {
NSString *employeeEducation;
}

  • (id)initWithName:(NSString *)name andAge:(NSInteger)age
    andEducation:(NSString *)education;
  • (void)print;
    @end

@implementation Employee

- (id)initWithName:(NSString *)name andAge:(NSInteger)age 
   andEducation: (NSString *)education {
      personName = name;
      personAge = age;
      employeeEducation = education;
      return self;
   }
- (void)print {
   NSLog(@"Name: %@", personName);
   NSLog(@"Age: %ld", personAge);
   NSLog(@"Education: %@", employeeEducation);
}

@end

int main(int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSLog(@”Base class Person Object”);
Person *person = [[Person alloc]initWithName:@”Raj” andAge:5];
[person print];
NSLog(@”Inherited Class Employee Object”);
Employee *employee = [[Employee alloc]initWithName:@”Raj”
andAge:5 andEducation:@”MBA”];
[employee print];
[pool drain];
return 0;
}

-derived class inherits all base class methods and variables with the following exceptions:

–variables declared in implementation file with the help of extensions is not accessible.

–methods declared in implementation file with the help of extensions is not accessible.

–in case the inherited class implements the method in base class, then the method in derived class is executed.

41
Q

Objective-C Polymorphism

A
  • having many forms
  • a call to a member function will cause a different function to be executed depending upon the type of the object that invokes the function

@interface Shape : NSObject {
CGFloat area;
}

  • (void)printArea;
  • (void)calculateArea;
    @end

@implementation Shape
- (void)printArea {
NSLog(@”The area is %f”, area);
}

  • (void)calculateArea {

}

@end

@interface Square : Shape {
CGFloat length;
}

  • (id)initWithSide:(CGFloat)side;
  • (void)calculateArea;

@end

@implementation Square
- (id)initWithSide:(CGFloat)side {
   length = side;
   return self;
}
  • (void)calculateArea {
    area = length * length;
    }
  • (void)printArea {
    NSLog(@”The area of square is %f”, area);
    }

@end

@interface Rectangle : Shape {
CGFloat length;
CGFloat breadth;
}

  • (id)initWithLength:(CGFloat)rLength andBreadth:(CGFloat)rBreadth;
    @end
@implementation Rectangle
- (id)initWithLength:(CGFloat)rLength andBreadth:(CGFloat)rBreadth {
   length = rLength;
   breadth = rBreadth;
   return self;
}
  • (void)calculateArea {
    area = length * breadth;
    }

@end

int main(int argc, const char * argv[]) {
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   Shape *square = [[Square alloc]initWithSide:10.0];
   [square calculateArea];
   [square printArea];
   Shape *rect = [[Rectangle alloc]
   initWithLength:10.0 andBreadth:5.0];
   [rect calculateArea];
   [rect printArea];        
   [pool drain];
   return 0;
}
42
Q

Objective-C Data Encapsulation

A

data encapsulation:
mechanism of bundling the data and the functions that use them

data abstraction:
mechanism of exposing only the interfaces and hiding the implementation details from the user.

@interface Adder : NSObject {
NSInteger total;
}

  • (id)initWithInitialNumber:(NSInteger)initialNumber;
  • (void)addNumber:(NSInteger)newNumber;
  • (NSInteger)getTotal;

@end

@implementation Adder
-(id)initWithInitialNumber:(NSInteger)initialNumber {
   total = initialNumber;
   return self;
}
  • (void)addNumber:(NSInteger)newNumber {
    total = total + newNumber;
    }
  • (NSInteger)getTotal {
    return total;
    }

@end

int main(int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Adder *adder = [[Adder alloc]initWithInitialNumber:10];
[adder addNumber:5];
[adder addNumber:4];

NSLog(@”The total is %ld”,[adder getTotal]);
[pool drain];
return 0;
}

43
Q

Objective-C Categories

A
  • adds behavior to existing class
  • can be declared for any class, even if you don’t have the original implementation source code.
  • any methods that you declare in a category will be available to all instances of the original class, as well as any subclasses of the original class.
  • at runtime, there’s no difference between a method added by a category and one that is implemented by the original class.

@interface NSString(MyAdditions)
+(NSString *)getCopyRightString;
@end

@implementation NSString(MyAdditions)

+(NSString *)getCopyRightString {
return @”Copyright TutorialsPoint.com 2013”;
}

@end

int main(int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *copyrightString = [NSString getCopyRightString];
NSLog(@”Accessing Category: %@”,copyrightString);

[pool drain];
return 0;
}

44
Q

Objective-C Extensions

A
  • similar to category but can only be added to a class for which the source code is available at compile time
  • are actually categories without the category name
  • often referred to as anonymous categories
  • cannot be declared for any class, only for the classes that we have original implementation of source code.
  • is adding private methods and private variables that are only specific to the class.
  • any method or variable declared inside the extensions is not accessible even to the inherited classes.

@interface SampleClass : NSObject {
NSString *name;
}

  • (void)setInternalID;
  • (NSString *)getExternalID;

@end

@interface SampleClass() {
NSString *internalID;
}

@end

@implementation SampleClass

  • (void)setInternalID {
    internalID = [NSString stringWithFormat:
    @”UNIQUEINTERNALKEY%dUNIQUEINTERNALKEY”,arc4random()%100];
    }
  • (NSString *)getExternalID {
    return [internalID stringByReplacingOccurrencesOfString:
    @”UNIQUEINTERNALKEY” withString:@””];
    }

@end

int main(int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
SampleClass *sampleClass = [[SampleClass alloc]init];
[sampleClass setInternalID];
NSLog(@”ExternalID: %@”,[sampleClass getExternalID]);
[pool drain];
return 0;
}

45
Q

Objective-C Protocols

A
  • declare the methods expected to be used for a particular situation
  • implemented in the classes conforming to the protocol

@protocol PrintProtocolDelegate
- (void)processCompleted;

@end

@interface PrintClass :NSObject {
id delegate;
}

  • (void) printDetails;
  • (void) setDelegate:(id)newDelegate;
    @end
@implementation PrintClass
- (void)printDetails {
   NSLog(@"Printing Details");
   [delegate processCompleted];
}
  • (void) setDelegate:(id)newDelegate {
    delegate = newDelegate;
    }

@end

@interface SampleClass:NSObject
- (void)startAction;

@end

@implementation SampleClass
- (void)startAction {
   PrintClass *printClass = [[PrintClass alloc]init];
   [printClass setDelegate:self];
   [printClass printDetails];
}

-(void)processCompleted {
NSLog(@”Printing Process Completed”);
}

@end

int main(int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
SampleClass *sampleClass = [[SampleClass alloc]init];
[sampleClass startAction];
[pool drain];
return 0;
}

46
Q

Objective-C Dynamic Binding

A
  • determining the method to invoke at runtime instead of at compile time
  • also referred to as late binding

@interface Square:NSObject {
float area;
}

  • (void)calculateAreaOfSide:(CGFloat)side;
  • (void)printArea;
    @end

@implementation Square
- (void)calculateAreaOfSide:(CGFloat)side {
area = side * side;
}

  • (void)printArea {
    NSLog(@”The area of square is %f”,area);
    }

@end

@interface Rectangle:NSObject {
float area;
}

  • (void)calculateAreaOfLength:(CGFloat)length andBreadth:(CGFloat)breadth;
  • (void)printArea;
    @end

@implementation Rectangle

  • (void)calculateAreaOfLength:(CGFloat)length andBreadth:(CGFloat)breadth {
    area = length * breadth;
    }
  • (void)printArea {
    NSLog(@”The area of Rectangle is %f”,area);
    }

@end

int main() {
   Square *square = [[Square alloc]init];
   [square calculateAreaOfSide:10.0];

Rectangle *rectangle = [[Rectangle alloc]init];
[rectangle calculateAreaOfLength:10.0 andBreadth:5.0];

NSArray *shapes = [[NSArray alloc]initWithObjects: square, rectangle,nil];
id object1 = [shapes objectAtIndex:0];
[object1 printArea];

id object2 = [shapes objectAtIndex:1];
[object2 printArea];

return 0;
}

47
Q

Objective-C Composite Objects

A
  • subclass within a class cluster that defines a class that embeds within it an object
  • class clusters group a number of private concrete subclasses under a public abstract superclass
  • composite object created by embedding a private cluster object in an object of our own design

@interface ValidatingArray : NSMutableArray {
NSMutableArray *embeddedArray;
}

+ validatingArray;

  • init;
  • (unsigned)count;
  • objectAtIndex:(unsigned)index;
  • (void)addObject:object;
  • (void)replaceObjectAtIndex:(unsigned)index withObject:object;
  • (void)removeLastObject;
  • (void)insertObject:object atIndex:(unsigned)index;
  • (void)removeObjectAtIndex:(unsigned)index;

@end

@implementation ValidatingArray
- init {
   self = [super init];
   if (self) {
      embeddedArray = [[NSMutableArray allocWithZone:[self zone]] init];
   }
   return self;
}

+ validatingArray {
return [[self alloc] init] ;
}

  • (unsigned)count {
    return [embeddedArray count];
    }
  • objectAtIndex:(unsigned)index {
    return [embeddedArray objectAtIndex:index];
    }
- (void)addObject:(id)object {
   if (object != nil) {
      [embeddedArray addObject:object];
   }
}
- (void)replaceObjectAtIndex:(unsigned)index withObject:(id)object; {
   if (index  0) {
      [embeddedArray removeLastObject];
   }
}
  • (void)insertObject:(id)object atIndex:(unsigned)index; {
    if (object != nil) {
    [embeddedArray insertObject:object atIndex:index];
    }
    }
  • (void)removeObjectAtIndex:(unsigned)index; {
    if (index
48
Q

Objective-C Foundation Framework

A
  • defines a base layer of Objective-C classes
  • provide a small set of basic utility classes.
  • make software development easier by introducing consistent conventions for things such as deallocation.
  • support Unicode strings, object persistence, and object distribution.
  • provide a level of OS independence to enhance portability.
49
Q

Objective-C Fast Enumeration

A

-helps in enumerating through a collection

int main() {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSArray *array = [[NSArray alloc]
initWithObjects:@”string1”, @”string2”,@”string3”,nil];

for(NSString *aString in array) {
NSLog(@”Value: %@”,aString);
}

[pool drain];
return 0;
}

50
Q

Objective-C Memory Management

A

MMR (Manual Retain-Release)

  • we own any object we create: We create an object using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy”
  • we can take ownership of an object using retain: A received object is normally guaranteed to remain valid within the method it was received in, and that method may also safely return the object to its invoker. We use retain in two situations −
  • in the implementation of an accessor method or an init method, to take ownership of an object we want to store as a property value.
  • to prevent an object from being invalidated as a side-effect of some other operation.
  • when we no longer need it, we must relinquish ownership of an object we own: We relinquish ownership of an object by sending it a release message or an autorelease message. In Cocoa terminology, relinquishing ownership of an object is therefore typically referred to as “releasing” an object.
  • you must not relinquish ownership of an object you do not own: This is just corollary of the previous policy rules stated explicitly.

@interface SampleClass:NSObject
- (void)sampleMethod;
@end

@implementation SampleClass
- (void)sampleMethod {
NSLog(@”Hello, World! \n”);
}

  • (void)dealloc {
    NSLog(@”Object deallocated”);
    [super dealloc];
    }

@end

int main() {

   /* my first program in Objective-C */
   SampleClass *sampleClass = [[SampleClass alloc]init];
   [sampleClass sampleMethod];

NSLog(@”Retain Count after initial allocation: %d”,
[sampleClass retainCount]);
[sampleClass retain];

NSLog(@”Retain Count after retain: %d”, [sampleClass retainCount]);
[sampleClass release];
NSLog(@”Retain Count after release: %d”, [sampleClass retainCount]);
[sampleClass release];
NSLog(@”SampleClass dealloc will be called before this”);

   // Should set the object to nil
   sampleClass = nil;
   return 0;
}

ARC (Automatic Reference Counting)

-the system uses the same reference counting system as MRR, but it inserts the appropriate memory management method calls for us at compile-time

@interface SampleClass:NSObject
- (void)sampleMethod;
@end

@implementation SampleClass
- (void)sampleMethod {
NSLog(@”Hello, World! \n”);
}

  • (void)dealloc {
    NSLog(@”Object deallocated”);
    }

@end

int main() {
   /* my first program in Objective-C */
   @autoreleasepool {
      SampleClass *sampleClass = [[SampleClass alloc]init];
      [sampleClass sampleMethod];
      sampleClass = nil;
   }
   return 0;
}