The following simple examples illustrate the contrast between creating a new object using alloc, using a convenience constructor, and using an accessor method.
The first example creates a new string object using alloc: It must therefore be released.
- (void)printHello { | 
NSString *string;  | 
string = [[NSString alloc] initWithString:@"Hello"];  | 
NSLog(string);  | 
[string release];  | 
}  | 
The second example creates a new string object using a convenience constructor: There is no additional work to do.
- (void)printHello { | 
NSString *string;  | 
string = [NSString stringWithFormat:@"Hello"];  | 
NSLog(string);  | 
}  | 
The third example retrieves a string object using an accessor method: As with the convenience constructor, there is no additional work to do.
- (void)printWindowTitle { | 
NSString *string;  | 
string = [myWindow title];  | 
NSLog(string);  | 
}  | 
No comments:
Post a Comment