See Also
Syntax
Methods
Methods called on objects
-
[object method];
-
[object method:input];
-
output = [object method:input];
Multi-param methods
-
BOOL result = [myData writeToFile:@"/tmp/log.txt" atomically:NO];
Declared in the header as:
-(BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile;
Class methods
-
NSString* some_str = [NSString string]; -- make a string
-
id some_object = [NSString string];
(id is 'mother of all objects')
Method parameters that are methods
- rather than
string blah* = new String(make_format()), do
NSString* some_str = [NSString stringWithFormat:[prefs format]];
Members and Accessors
Classic Style (Obj-C 1.0)
- Set:
[thing setName:@"name for thing"];
- Get:
out = [thing name]; - NOTE: name is actually a METHOD. Obj-C convention - not named getName
Dot Style (Obj-C 2.0)
-
thing.name = @"name for thing";
-
out = thing.name;
- NOTE: - use dot style only for getters and setters
Making Objects
Automatic style:
(makes an autoreleased object - garbage collection used to free) :
-
NSString* string = [NSString string];
Manual Style:
(you must free it)
-
= NSString* string = [[NSString alloc] init];=
Like: StringClass* string = StringClass.factory();
string.init();
- Or,
NSNumber* val = [[NSNumber alloc] initWithFloat:1.0];
- Later, you must do
[string release];
Defining Objects
#import <Cocoa/Cocoa.h> // import is nice; won't let you import file more than once
@interface Name : NSObject {
NSString* first;
NSString* last;
// 'get' accessors; '-' means instance method. Assumed return type is 'id'
- first;
- last;
// can alternatively specify return type
- (NSString*) first
// 'set' accessors
- (void) setFirst: (NSString*)input;
+ makeMatt; // '+' means class method
}
@end
Implementing Objects
@implementation Name
- (NSString*) first { return first; }
- (void) setFirst: (NSString*)input
{
// without GC
[first autorelease];
// also, just 'release' - immediate free - 'autorelease' keeps at least till func over
first = [input retain];
// alternatively, with GC
first = input;
}
- (id) init
{
if ( self = [super init] ) // let superclass do its init, = succeeds if init was ok
{
[ self setFirst:@"Joe"];
[ self setLast:@"Schmoe"];
}
return self; // MSW: is 'self' == 'this' ?
}
- (void) dealloc // or use 'finalize' if no GC
{
[first release]; // don't need autorelease; release a bit faster
[last release];
[super dealloc];
}
@end
--
MattWalsh - 03 Sep 2009