Ale*_*lex 7 macos initialization objective-c
我有两种不同的方法来初始化我的objective-c类.一个是默认值,一个是配置参数.现在,当谈到objective-c时我很绿,但是我已经实现了这些方法,我想知道是否有更好的(更正确/更好的风格)方式来处理初始化而不是我的方式.意思是,我是否按照标准和良好的风格编写了这些初始化函数?它只是不正确检查是否存在selfPtr然后基于此返回.
下面是我的类头和实现文件.此外,如果你发现任何其他错误或邪恶的东西,请告诉我.我是一名C++/Javascript开发人员,他正在学习Objective-c作为业余爱好,并感谢您提供的任何提示.
#import <Cocoa/Cocoa.h>
// class for raising events and parsing returned directives
@interface awesome : NSObject {
// silence is golden. Actually properties are golden. Hence this emptiness.
}
// properties
@property (retain) SBJsonParser* parser;
@property (retain) NSString* eventDomain;
@property (retain) NSString* appid
// constructors
-(id) init;
-(id) initWithAppId:(id) input;
// destructor
-(void) dealloc;
@end
Run Code Online (Sandbox Code Playgroud)
#import "awesome.h"
#import "JSON.h"
@implementation awesome
- (id) init {
if (self = [super init]) {
// if init is called directly, just pass nil to AppId contructor variant
id selfPtr = [self initWithAppId:nil];
}
if (selfPtr) {
return selfPtr;
} else {
return self;
}
}
- (id) initWithAppId:(id) input {
if (self = [super init]) {
if (input = nil) {
input = [[NSString alloc] initWithString:@"a369x123"];
}
[self setAppid:input];
[self setEventDomain:[[NSString alloc] initWithString:@"desktop"]];
}
return self;
}
// property synthesis
@synthesize parser;
@synthesize appid;
@synthesize eventDomain;
// destructor
- (void) dealloc {
self.parser = nil;
self.appid = nil;
self.eventDomain = nil;
[super dealloc];
}
@end
Run Code Online (Sandbox Code Playgroud)
谢谢!
d11*_*wtq 14
当一个初始化程序只使用一些默认参数执行更复杂的初始化程序时,请将其调用为:
-(id)init {
return [self initWithAppID:nil];
}
-(id)initWithAppID:(id)input {
if (self = [super init]) {
/* perform your post-initialization logic here */
}
return self;
}
Run Code Online (Sandbox Code Playgroud)
通常,您尝试将其中一个初始化程序设为"指定的初始值设定项",这意味着它始终被调用.在这种情况下-initWithAppID:.