lab2: objective-c basicsjcransh/ipad/downloads/labs/lab2.pdfthe work in managing memory •...
Post on 10-Sep-2020
2 Views
Preview:
TRANSCRIPT
Lab2: Objective-C Basics
Justin Cranshawjcransh@cs.cmu.edu
Jan 25, 2012
Goals
• Questions and Review for HW1
• Review basic principals of Objective-C
• Review Testing
• Introduce Foundation Collection Classes
ClassesImplementation (Car.m)Header File (Car.h)
// interface@interface Car : NSObject
- (void) setColor:(NSString *)color;
@end
Method and property
declarations
// implementation@implementation Car
{ // instance variables go here _color = NSString *color;}
- (void) setColor:(NSString *)color { _color = color;}
@end
ClassesImplementation (Car.m)Header File (Car.h)
// interface@interface Car : NSObject
- (void) setColor:(NSString *)color;
@end
You can have private methods here
Method and property
declarations
// private interface@interface Car() - (void) somethingPrivate@end
// implementation@implementation Car
{ // instance variables go here NSString *_color;}
- (void) setColor:(NSString *)color { _color = color;}
- (void) somethingPrivate { }
@end
Method Names
- (NSString*) adjustSeatAtPosition:(int)whichSeat toHeight:(float)height andBackAngle:(float)angle;
[myCar adjustSeatAtPosition:0 toHeight:1.0f andBackAngle:45.0f];
Method Names
We think of method names in Objective-C as being interleaved between the arguments by argument names.
Declaring Methods:
Invoking Methods:
Use this convention in your homework!
Objective-C:
- (NSString*) adjustSeatAtPosition:(int)whichSeat toHeight:(float)height andBackAngle:(float)angle;
[myCar adjustSeatAtPosition:0 toHeight:1.0f andBackAngle:45.0f];
Java:
public String adjustSeatHeightAndAngle(int whichSeat,float height,float angle) { }
myCar.adjustSeatHeightAndAngle(0,1.0f,45.0f);
Method Names: Java Comparison
Creating Objects
• To create class instances we use alloc/init:
• alloc allocates the necessary memory for a car, and init initializes the object
testCar = [[Car alloc] init];
Creating Objects
• We define initializers like so:
• A designated initializer is one that initializes all values
- (id) initWithColor:(NSString*) color { if (self = [super init]) { _color = color; } return self;}
Properties
Properties
• Properties provide a way to automate the implementation of instance variable accessors.
• The declaration of properties provide a clear description of how accessors behave
• Compiler does the tedious work for you with @synthesize
// implementation@implementation Car
@synthesize color = _color;
@end
// implementation@implementation Car
{ // instance variables go here _color = NSString *color;}
- (NSString *) color { return _color;}
- (void) setColor:(NSString *)color { _color = color;}
@end
// interface@interface Car : NSObject
@property (readwrite, strong) NSString *color;
@end
With PropertiesWithout Properties// interface@interface Car : NSObject
- (NSString *) color;- (void) setColor:(NSString *)color;
@end
// invocationNSString *oldColor = myCar.color;myCar.color = @"Candy Apple Red";
// invocationNSString *oldColor = [myCar color];[myCar setColor:@"Candy Apple Red"];
Automatic Reference Counting
Automatic Reference Counts
• Pre-compilation step that simplifies some fo the work in managing memory
• Introduced in Xcode 4.2
• Requires that you define how your classes manage references to each other
ARC (new to Xcode 4.2)Reference Counting (old)// alloc the objectNSString *myCar = [[Car alloc] init];
// drive the car for a while
// release the memory when done[myCar release];
// alloc the objectNSString *myCar = [[Car alloc] init];
// drive the car for a while
// the compiler will add the release// code for us
Properties: strong and weak References
In order for the compiler to know when to properly deallocate resources, we need to qualify the relationships between our classes.
• Strong: Tell the compiler not to release the declared object while I’m (the self object) still around using it
• Weak: Tell the compiler it’s ok for the declared object to be released while I’m (the self object) still around using it
Object 1 Object 2
Strong
As long as Object 1 is retained in memory,Object 2 will be retained.
Object 1 Object 2
Weak
If there are no other active references toObject 2, it will be released, even if Object 1
is still retained in memory.
Object 1 Object 2
Strong
These Objects will never be released.Watch out for this!
Unless this is your intended behavior, this could be a leak.
Strong
Testing
Testing
• Some people expressed confusion about what tests are supposed to do.
• If you’re initializers and/or getters/setters are validating the range of ivar values, why use tests?
Testing
Car Class Test Class
We specify in our implementation, the allowable
“behavior” of a car. Our code should ensure that only legal behaviors are allowed
(i.e. you can’t turn the wheels backwards).
Testing is meant to make sure that we’ve done our jobs
correctly as coders in specifying this behavior. Here we want to instantiate a car
object and make sure it doesn’t behaving in ways that
aren’t allowed.
Testing
Car Class Test Class
Value checks in getters and setters are making sure users
of our API are using it correctly.
Tests are to make sure that we’ve done our job as
coders properly.
Testing
Car Class Test Class
- (void) setWheelAngle:(float)wheelAngle { if (wheelAngle < -45.0f || wheelAngle > 45.0f) { return; } _wheelAngle = wheelAngle;}
- (void)testWheelAngle{ testCar.wheelAngle = 30.0f; STAssertEquals(testCar.wheelAngle, 30.0f, @"Setting failed!"); testCar.wheelAngle = 300.0f; STAssertEquals(testCar.wheelAngle, 300.0f, @"Setting failed!"); }
Foundation Collections
• Like most languages, Objective-C has a number of Collection Classes for storing and managing groups of objects.
• We’ll briefly given an overview of the different types of collections in Objective-C
Collection Types
• Arrays (ordered and indexed): NSArray, NSMutableArray
• Dictionaries (unordered, keyed access): NSDictionary, NSMutableDictionary
• Sets (unordered, membership checks): NSSet, NSMutableSet
Collection Examples:Iterating over an array
NSArray *carColors = [NSArray arrayWithObjects:@"Red", @"Blue",@"Green",nil];int num = [carColors count];
for (int i=0; i<count; i++) NSLog(@"Car number %i is %@", i, [carColors objectAtIndex:i]);
for (NSString *color in carColors) NSLog(@"My color is %@", color);
Collection Examples:Adding and removing elements
NSMutableArray *carColors = [NSArray arrayWithObjects:@"Black", @"Blue",nil];[carColors addObject:@"Candy Apple Red"];[carColors insertObject:@"Silver" atIndex:1];[carColors removeObjectAtIndex:0];[carColors removeObject:@"Blue"];
Collection Examples:Sorting a Dictionary
NSMutableDictionary *priceByPart = [NSArray arrayWithObjectsAndKeys: [NSNumber numberWithInt:100], @"Starter", [NSNumber numberWithInt:1500], @"Transmission", [NSNumber numberWithInt:20], @"Hose", nil];
NSArray *sortedParts = [priceByPart keysSortedByValueUsingSelector:@selector(compare:)];
top related