加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – 目标C:类方法说明

发布时间:2020-12-14 18:56:01 所属栏目:百科 来源:网络整理
导读:作为从C到Objective-C的过渡过程的一部分,我深入阅读了 Cocoa and Objective C Up and Running.书 在其中一本书代码示例中,有一条线对我目前的知识水平没有意义: 它是类方法(Photo *)photo;的声明. 有人可以解释一下原因吗,为什么作者决定采用这种方法(照片
作为从C到Objective-C的过渡过程的一部分,我深入阅读了 Cocoa and Objective C Up and Running.书

在其中一本书代码示例中,有一条线对我目前的知识水平没有意义:

它是类方法(Photo *)photo;的声明.

有人可以解释一下原因吗,为什么作者决定采用这种方法(照片*)照片;将它声明为类方法而不是实例方法?

我已经研究了这个理论,即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 = [input retain];
}


- (void) setPhotographer: (NSString *)input {
    [photographer autorelease];
    photographer = [input retain];
}


- (void)dealloc
{
    [self setCaption:nil];
    [self setPhotographer:nil];

    [super dealloc];
}

@end

解决方法

Could anybody explain me the reason,please,why the author had decided for the method (Photo*) photo; to declare it as a class method instead of instance method?

它基本上是构造函数的包装器.注意来源:

+ (Photo*) photo {
    Photo* newPhoto = [[Photo alloc] init];
    return [newPhoto autorelease];
}

分配新照片,初始化,标记为自动释放,然后返回.由于它创建了对象,因此还没有对象可以进行操作,因此需要使用类方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读