Objective C Week 4 Tuesday

  • Uploaded by: William Smith
  • 0
  • 0
  • June 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Objective C Week 4 Tuesday as PDF for free.

More details

  • Words: 1,432
  • Pages: 30
September 10, 2009

Loops, Decisions, and Objects (oh my)

September 10, 2009

Loops

· for loop · while loop · do. .while loop

September 10, 2009

The For Loop

for ( n = 1; n <= 200; n = n + 1 ) triangularNumber += n;

September 10, 2009

The While Loop while ( v != 0 ) { temp = u % v; u = v; v = temp; }

September 10, 2009

The Do...While Loop do { right_digit = number % 10; NSLog (@"%i", right_digit); number /= 10; } while ( number != 0 );

September 10, 2009

The break Statement Sometimes when executing a loop, you'll want to leave the loop as soon as a certain condition occurs—for instance, maybe you detect an error condition or reach the end of your data prematurely. You can use the break statement for this purpose. Execution of the break statement causes the program to immediately exit from the loop it is executing, whether it's a for, while, or do loop. Subsequent statements in the loop are skipped and execution of the loop is terminated. Execution continues with whatever statement follows the loop. If a break is executed from within a set of nested loops, only the innermost loop in which the break is executed is terminated. The format of the break statement is simply the keyword break followed by a semicolon, like so: break;

September 10, 2009

The continue Statement The continue statement is similar to the break statement, except that it doesn't cause the loop to terminate. At the point that the continue statement is executed, any statements that appear after the continue statement up to the end of the loop are skipped. Execution of the loop otherwise continues as normal. The continue statement is most often used to bypass a group of statements inside a loop based on some condition, but then to otherwise continue executing the loop. The format of the continue statement is as follows: continue;

September 10, 2009

Decisions · If · If...else · Case

September 10, 2009

The If Statement if ( number < 0 )          number = -number;

September 10, 2009

The If...Else Statement -(double) convertToNum {     if (denominator != 0)         return (double) numerator / denominator;     else         return 0.0; }

September 10, 2009

Nested Decisions if ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') )         NSLog (@"It's an alphabetic character.");     else if ( c >= '0' && c <= '9' )        NSLog (@"It's a digit.");     else        NSLog (@"It's a special character.");

September 10, 2009

September 10, 2009

September 10, 2009

The Case (switch) Statement   switch ( operator ) {        case '+':           [deskCalc add: value2];           break;        case '-':           [deskCalc subtract: value2];           break;        case '*':           [deskCalc multiply: value2];           break;        case '/':           [deskCalc divide: value2];           break;        default:           NSLog (@"Unknown operator.");           break;     }

September 10, 2009

The Conditional Operator Perhaps the most unusual operator in the Objective-C language is one called the conditional operator. Unlike all other operators in Objective-C—which are either unary or binary operators—the conditional operator is a ternary operator; that is, it takes three operands. The two symbols used to denote this operator are the question mark ( ?) and the colon (:). The first operand is placed before the ?, the second between the ? and the :, and the third after the :. The general format of the conditional expression is shown here: condition ? expression1 : expression2

September 10, 2009

Initializing Classes The process of initializing an object followed by setting it to some initial values is often combined into a single method. For example, you can define an initWith:: method that initializes a fraction and sets its numerator and denominator to the two (unnamed) supplied arguments. A class that contains many methods and instance variables in it commonly has several initialization methods as well. For example, the Foundation framework's NSArray class contains the following six initialization methods: initWithArray: initWithArray:copyItems: initWithContentsOfFile: initWithContentsOfURL: initWithObjects: initWithObjects:count: An array might be allocated and then initialized with a sequence like this:   myArray = [[NSArray alloc] initWithArray: myOtherArray];

September 10, 2009

September 10, 2009

You should adhere to the following two strategies when writing initializers. If your class contains more than one initializer, one of them should be your designated initializer and all the other initialization methods should use it. Typically, that is your most complex initialization method (usually, the one that takes the most arguments). Creating a designated initializer centralizes your main initialization code in a single method. Anyone subclassing your class can then override your designated initializer, to ensure that new instances are properly initialized. Ensure that any inherited instance variables get properly initialized. The easiest way to do that is to first invoke the parent's designated initialization method, which is most often init. After that, you can initialize your own instance variables.

September 10, 2009

-(Fraction *) initWith: (int) n: (int) d {   self = [super init];   if (self)      [self setTo: n over: d];   return self; }

   a = [[Fraction alloc] initWith: 1: 3];    b = [[Fraction alloc] initWith: 3: 7];

September 10, 2009

September 10, 2009

September 10, 2009

NSNumber          *myNumber

intNumber = [NSNumber numberWithInteger: 100];     myInt = [intNumber integerValue];     NSLog (@"%li", (long) myInt);     // long value     myNumber = [NSNumber numberWithLong: 0xabcdef];     NSLog (@"%lx", [myNumber longValue]);     // char value     myNumber = [NSNumber numberWithChar: 'X'];     NSLog (@"%c", [myNumber charValue]);

September 10, 2009

The NSNumber class contains many methods that allow you to create NSNumber objects with initial values. For example, the line   intNumber = [NSNumber numberWithInteger: 100]; creates an object from an integer whose value is 100.

September 10, 2009

Creation and Initialization Class Method

Initialization Instance Method

Retrieval Instance Method

numberWithChar:

initWithChar:

charValue

numberWithUnsignedChar:

initWithUnsignedChar:

unsignedCharValue

numberWithShort:

initWithShort:

shortValue

numberWithUnsignedShort:

initWithUnsignedShort:

unsignedShortValue

numberWithInteger:

initWithInteger:

integerValue

numberWithUnsignedInteger:

initWithUnsignedInteger:

unsignedIntegerValue

numberWithInt:

initWithInt:

intValue

numberWithUnsignedInt:

initWithUnsignedInt:

unsignedIntValue

numberWithLong:

initWithLong:

longValue

numberWithUnsignedLong:

initWithUnsignedLong:

unsignedLongValue

numberWithLongLong:

initWithLongLong:

longlongValue

numberWithUnsignedLongLong:

initWithUnsignedLongLong:

unsignedLongLongValue

numberWithFloat:

initWithFloat:

floatValue

numberWithDouble:

initWithDouble:

doubleValue

numberWithBool:

initWithBool:

boolValue

September 10, 2009

Mutable Versus Immutable Objects When you create a string object by writing an expression such as @"Programming is fun" you create an object whose contents cannot be changed. This is referred to as an immutable object. The NSString class deals with immutable strings. Frequently, you'll want to deal with strings and change characters within the string. For example, you might want to delete some characters from a string or perform a search-and-replace operation on a string. These types of strings are handled through the NSMutableString class.

September 10, 2009

Mutable Strings The NSMutableString class can be used to create string objects whose characters can be changed. Because this class is a subclass of NSString , all NSString 's methods can be used as well. When we speak of mutable versus immutable string objects, we talk about changing the actual characters within the string. Either a mutable or an immutable string object can always be set to a completely different string object during execution of the program. For example, consider the following:   str1 = @"This is a string";      ...   str1 = [str1 substringFromIndex: 5]; In this case, str1 is first set to a constant character string object. Later in the program, it is set to a substring. In such a case, str1 can be declared as either a mutable or an immutable string object. Be sure you understand this point.

September 10, 2009

Method

Description

+(id) stringWithCapacity: Creates a string initially containing size characters. size -(id) initWithCapacity: size

Initializes a string with an initial capacity of size characters.

-(void) setString: nsstring

Sets a string to nsstring .

-(void) appendString: nsstring

Appends nsstring to the end of the receiver.

-(void) deleteCharactersInRange: range

Deletes characters in a specified range.

-(void) insertString: nstring atIndex: i

Inserts nsstring into the receiver starting at index i.

-(void) Replaces characters in a specified range with nsstring . replaceCharactersInRange: range withString: nsstring -(void) replaceOccurrencesOf String: nsstring withString: nsstring2 options: opts range: range

Replaces all occurrences of nsstring with nsstring2 within a specified range and according to options opts. Options can include a bitwise-ORed combination of NSBackwardsSearch (the search starts from the end of range), NSAnchoredSearch (nsstring must match from the beginning of the range only), NSLiteralSearch (performs a byte-by-byte comparison), and NSCaseInsensitiveSearch .

September 10, 2009

September 10, 2009

NSArray  *monthNames = [NSArray  arrayWithObjects:       @"January", @"February", @"March", @"April",       @"May", @"June", @"July", @"August", @"September",       @"October", @"November", @"December", nil ];    // Now list all the elements in the array    NSLog (@"Month   Name");    NSLog (@"=====   ====");    for (i = 0; i < 12; ++i)       NSLog (@" %2i     %@", i + 1, [monthNames objectAtIndex: i]);

September 10, 2009

Lab Time!

Related Documents


More Documents from "William Smith"