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

objective-c – 目标C:类方法说明,第1张

概述作为从C到Objective-C的过渡过程的一部分,我深入阅读了 Cocoa and Objective C Up and Running.书 在其中一本书代码示例中,有一条线对我目前的知识水平没有意义: 它是类方法(Photo *)photo;的声明. 有人可以解释一下原因吗,为什么作者决定采用这种方法(照片*)照片;将它声明为类方法而不是实例方法? 我已经研究了这个理论,即instane方法类 作为从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];}

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

总结

以上是内存溢出为你收集整理的objective-c – 目标C:类方法说明全部内容,希望文章能够帮你解决objective-c – 目标C:类方法说明所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1035117.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-24
下一篇 2022-05-24

发表评论

登录后才能评论

评论列表(0条)

保存