作为我从 C++ 到 Objective-C 的过渡过程的一部分,我深入阅读了书 Cocoa and Objective C Up and Running.
在书中的一个代码示例中,有一行对我目前的知识水平来说没有意义:
是类方法+(Photo*) photo;
的声明。
谁能给我解释一下为什么作者决定将方法 (Photo*) photo;
声明为类方法 而不是 < strong>实例方法?
我研究过这个理论,instane 方法类似于类成员函数,而类方法类似于 C++ 中的静态函数。但这仍然没有回答我的问题。
声明代码如下:
#import <Foundation/Foundation.h>
@interface Photo : NSObject{
NSString* caption;
NSString* photographer;
}
+ (Photo*) photo;
- (NSString*) caption;
- (NSString*) photographer;
- (void) setCaption: (NSString*)input;
- (void) setPhotographer: (NSString*)input;
@end
实现代码如下:
#import "Photo.h"
@implementation Photo
- (id)init
{
self = [super init];
if (self) {
[self setCaption:@"Default Caption"];
[self setPhotographer:@"Default Photographer"];
}
return self;
}
+ (Photo*) photo {
Photo* newPhoto = [[Photo alloc] init];
return [newPhoto autorelease];
}
- (NSString*) caption {
return caption;
}
- (NSString*) photographer {
return photographer;
}
- (void) setCaption:(NSString *)input {
[caption autorelease];
caption = [input retain];
}
- (void) setPhotographer: (NSString *)input {
[photographer autorelease];
photographer = [input retain];
}
- (void)dealloc
{
[self setCaption:nil];
[self setPhotographer:nil];
[super dealloc];
}
@end
最佳答案
+ (Photo*) photo
方法是一个 Factory Method封装了创建 Photo
类对象的细节。
A Factory Method enforces encapsulation, and allows an object to be requested without inextricable coupling to the act of creation.
在此特定示例中,工厂方法隐藏的信息是 memory management ,因为客户端不需要担心释放返回的对象。
在 Objective-C API 中的常见做法是在返回相同类的自动释放对象的类中提供工厂方法。这些方法不得包含任何单词“alloc”、“new”、“copy”或“mutableCopy”,根据约定,这些单词表示调用者不拥有返回的对象,即它不必须明确发布。
相关资源:
关于objective-c - Objective-C : Class Method Explanation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6350770/