Objective C Notes
- Links
- .h vs .m
- this
- Null
- Import
- Properties
- Arrays
- Class methods
- Booleans
- Memory Management
- Hello World
- Dictionaries
- Code Blocks
Links
- Free course from Standford: Coding Together: Developing iOS 6 Apps for iPhone and iPad (Winter 2013)
.h vs .m
Everything in .m files is private. Everything in .h files is public.
this
For a pointer to the instance of an object that the currently executing code points to, use keyword self
.
Null
Use keyword nil
in objectivec. nil
is actually just 0, but indicates a special usage of 0.
Import
#import <Foundation/Foundation.h>
No problem importing entire library because import is smart and pre-compiles stuff so it's really efficient.
Properties
Think: "setter" and "getter".
Arrays
No types in Arrays. Arrays can hold any type and even mixed types of objects
Class methods
Instance methods start with minus -
. Static (or Class) methods start with +
;
Declaration
@property (strong, nonatomic) NSString *contents;
Can change the name of the getter
@property (nonatomic, getter=isFaceUp) BOOL *faceUp;
nonatomic
keyword means that this property is not thread safe.
Implementation
Setter and Getter implementations are automatic. But it's possible to customize the implementation like so:
@synthesize contents = _contents;
- (NSString *)contents
{
return _contents;
}
- (void)setContents:(NSString *)contents
{
_contents = contents;
}
If you implement both setter and getter, you gotta add the @synthesize
like this
@synthesize name = _name;
Booleans
C doesn't have notion of boolean. Objective C introduces a primitive type called BOOL
. Values can be YES
or NO
.
Memory Management
No Garbage collection.
All variables are pointers to space in the heap.
Reference Counting. As soon as no one points to memory, it's cleaned up.
Automatic(!) reference counting. strong
means keep object in the heap until I'm no longer pointing to it. weak
means keep object around as long as someone else points to it.
Hello World
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSString *name = @"Dave";
NSLog(@"Hello, %@", name);
}
return 0;
}
Dictionaries
NSDictionary *inventory = @{
@"Mercedes-Benz SLK250" : [NSNumber numberWithInt:13],
@"Mercedes-Benz E350" : [NSNumber numberWithInt:22],
@"BMW M3 Coupe" : [NSNumber numberWithInt:19],
@"BMW X6" : [NSNumber numberWithInt:16],
};
NSLog(@"There are %@ X6's in stock", inventory[@"BMW X6"]);
for (id key in inventory) {
NSLog(@"There are %@ %@'s in stock", inventory[key], key);
}
Code Blocks
void (^myFirstBlock)(void) = ^{
NSLog(@"Hi from inside a block");
};