2. Announcements
You should have received an e-mail by now
If you received e-mail approving enrollment, but are not in Axess, do it!
If you have any questions, please ask via e-mail or after class.
If you have not installed SDK and
gotten it working, talk to us after class.
Homework
Strongly recommend trying a submission today even if you’re not yet done
Multiple attempted submissions is no problem
Assignments are to be done individually (except approved pairs for final project)
Honor code applies
Any questions about the homework?
Thursday, April 29, 2010
3. Communication
E-mail
Questions are best sent to cs193p@cs.stanford.edu
Sending directly to instructor or TA’s risks slow response.
Web Site
Very Important!
http://cs193p.stanford.edu
All lectures, assignments, code, etc. will be there.
This site will be your best friend when it comes to getting info.
Thursday, April 29, 2010
4. Today’s Topics
Objective-C
Instance Variables
Methods (Class and Instance)
Properties
Dynamic vs. Static Binding
Introspection
Protocols and Delegates
Foundation Framework
NSObject, NSString, NSMutableString
NSNumber, NSValue, NSData, NSDate
NSArray, NSDictionary, NSSet
NSUserDefaults, etc.
Memory Management
Allocating and initializing objects
Reference Counting
Thursday, April 29, 2010
5. Instance Variables
By default, they are “protected”
Only methods in the class itself and subclasses can see them
Can be marked private with @private
Can be marked public with @public
Don’t do it! Use properties instead. Later.
@interface Ship : Vehicle
{
Size size;
@private
int turrets;
@public
NSString *dontDoThisString;
}
Thursday, April 29, 2010
6. Methods
If public, declare them in .h file.
Public or private, implement them in .m file.
- (NSArray *)findShipsAtPoint:(CGPoint)bombDrop withDamage:(BOOL)damaged;
1. Specify class method with + or instance method with - (more on this later)
2. Then return type in parentheses (can be void if returns nothing)
3. Then first part of name of method, always ending in : unless zero args
4. Then type of first argument in parentheses
5. Then name of first argument
6. If more arguments, next comes a required space, then repeat 3-5
7. Then semicolon if declaring , or code inside { } if implementing
Spaces allowed between any of the above steps, but no spaces in step 3 or 5
Thursday, April 29, 2010
7. Instance Methods
Declarations start with a - (a dash)
“Normal” methods you are used to
Instance variables usable inside implementation
Receiver of message can be self or super too
self calls method in calling object (recursion okay)
super calls method on self, but uses superclass’ implementation
s
If a superclass calls a method on self, it will use your implementation
Calling syntax:
BOOL destroyed = [ship dropBomb:bombType at:dropPoint];
Thursday, April 29, 2010
8. Class Methods
Declarations start with a + (a plus sign)
Usually used to ask a class to create an instance
Sometimes hands out “shared” instances
Or performs some sort of utility function
Not sent to an instance, so no instance
variables can be used in the implementation
of a class method (and be careful about self
in a class method ... it means the class object)
Calling syntax:
Ship *ship = [Ship shipWithTurrentCount:3];
Ship *mother = [Ship motherShip];
int size = [Ship turretCountForShipSize:shipSize];
Thursday, April 29, 2010
9. Properties
Note lowercase “o” then uppercase “O”
Replaces Use this convention for properties.
- (double)operand;
- (void)setOperand:(double)anOperand;
with
@property double operand;
Implementation replaced with ...
@synthesize operand; / if there’s an instance variable operand
/
@synthesize operand = op; / if correspon ding ivar is op
/
Callers use dot notation to set and get
double x = brain.operand;
brain.operand = newOperand;
Thursday, April 29, 2010
10. Properties
Properties can be “read only” (no setter)
@property (readonly) double operand;
You can use @synthesize and still implement
the setter or the getter yourself (one of them)
- (void)setMaximumSpeed:(int)speed
{
if (speed > 65) {
speed = 65;
}
maximumSpeed = speed;
}
@synthesize maximumSpeedwould still create
the getter even with above implementation
Thursday, April 29, 2010
11. Properties
Using your own (self’s) properties
What does this code do?
- (int)maximumSpeed
{
if (self.maximumSpeed > 65) {
return 65;
} else {
return maximumSpeed;
}
}
Infinite loop!
Thursday, April 29, 2010
12. nil
nil is the value that a variable which is a
pointer to an object (id or Foo *) has when it
is not currently pointing to anything.
Like “zero” for a primitive type (int, double, etc.)
(actually, it is not just “like” zero, it is zero)
NSObject sets all its instance variables to “zero”
(thus nil for objects)
Can be implicitly tested in an if statement:
if (obj) { } means “if the obj pointer is not nil”
Sending messages to nil is (mostly) A-OK!
If the method returns a value, it will return 0
Be careful if return value is a C struct though! Results undefined.
e.g. CGPoint p = [obj getLocation]; / if obj is nil, p undefined
/
Thursday, April 29, 2010
13. BOOL
BOOL is Objective-C’ boolean value
s
Can also be tested implicitly
YES means “true,” NO means “false”
NO is zero, YES is anything else
if (flag) { } means “if flag is YES”
if (!flag) { } means “if flag is NO”
if (flag == YES) { } means “if flag is YES”
if (flag != NO) { } means “if flag is not NO”
Thursday, April 29, 2010
14. Dynamic vs. Static
NSString * versus id
id * (almost never used, pointer to a pointer)
Compiler can check NSString *
Compiler will accept any message sent to id
that it knows about (i.e. it has to know some
object somewhere that knows that message)
“Force” a pointer by casting: (NSString *)foo
Regardless of what compiler says, your
program will crash if you send a message to
an object that does not implement that method
Thursday, April 29, 2010
15. Examples
@interface Ship : Vehicle
- (void)shoot;
@end
Ship *s = [[Ship alloc] init];
[s shoot];
Vehicle *v = s;
[v shoot]; / compiler will warn, no crash at runtime in this case
/
Ship *castedVehicle = (Ship *)someVehicle; / dangerous!!!
/
[castedVehicle shoot]; / compiler won’t warn, might crash
/
id obj = ...;
[obj shoot]; / compiler won’t warn, might crash
/
[obj lskdfjslkfjslfkj]; / compiler will warn, runtime crash
/
[(id)someVehicle shoot]; / no warning, might crash
/
Vehicle *tank = [[Tank alloc] init];
[(Ship *)tank shoot]; / no warning, crashes at runtime
/
Thursday, April 29, 2010
16. Introspection
isKindOfClass:
Can be sent to any object and takes inheritance into account
Takes a Class object as its argument (where do I get one?)
[NSString class] or [CalculatorBrain class] or [obj class]
Syntax: if ([obj isKindOfClass:[NSString class]]) {
isMemberOfClass:
Can be sent to any object but does NOT take inheritance into account
Syntax: if ([obj isMemberOfClass:[NSString class]]) {
This would be false if obj were NSMutableString
className
Returns the name of the class as an NSString
Syntax: NSString *name = [obj className];
Thursday, April 29, 2010
17. Introspection
respondsToSelector:
Can be sent to any NSObject to find out if it implements a certain method
Needs a special method token as its argument (a “selector”)
@selector(shoot) or @selector(foo:bar:)
Syntax: if ([obj respondsToSelector:@selector(shoot)]) {
SEL versus @selector()
The “type” of a selector is SEL, e.g., - (void)performSelector:(SEL)action
Important use: set up target/action outside of Interface Builder
Syntax: [btn addTarget:self action:@selector(shoot) ...]
performSelector:
Send a message to an NSObject using a selector
Syntax: [obj performSelector:@selector(shoot)]
Syntax: [obj performSelector:@selector(foo:) withObject:x]
Thursday, April 29, 2010
18. Introspection
Example
id anObject = ...;
SEL aSelector = @selector(someMethod:);
if ([anObject respondsToSelector:aSelector]) {
[anObject performSelector:aSelector withObject:self];
}
Thursday, April 29, 2010
19. Foundation Framework
NSObject
Base class for pretty much every object in iPhone SDK Frameworks
Implements memory management primitives (more on this in a moment)
and introspection
- (NSString *)description is a useful method to override, it’ %@ in NSLog
s
NSString
International (any language) strings
Used throughout all of iPhone SDK instead of C’s char *
Cannot be modified!
Usually returns you a new NSString when you ask it to do something
Tons of utility functions (case, URLs, conversion to/from lots of other
types, substrings, file system paths, and much much more!)
Compiler will create a constant one for you with @”foo”
NSMutableString
Mutable version of NSString
Can do some of the things NSString can do without making a new one
Thursday, April 29, 2010
20. Foundation Framework
NSNumber
Object wrapper around primitive types: int, float, double, BOOL, etc.
Use it when you want to store those in an NSArray or other object
NSValue
Generic object wrapper for any non-object data type.
Useful for wrapping graphics things like a CGPoint or CGRect
NSData
“Bag of bits”
Used to save/restore/transmit data throughout the SDK
NSDate
Can be used to find out the time now or store a past/future time
See also NSCalendar, NSDateFormatter, NSDateComponents
Thursday, April 29, 2010