joh*_*ohn 1 cocoa-touch coding-style objective-c object-initializers
这是我现在拥有的init,
- (id)init
{
self = [super init];
if (self) {
self.url = [[NSURL alloc] init];
self.blurb = [[NSString alloc] init];
self.author = [[NSString alloc] init];
}
return self;
}
Run Code Online (Sandbox Code Playgroud)
它什么也不做,但我有一个称为另一种方法initWithObject:将使用它的参数来填充实例变量url,blurb和author.我不知道我应该怎么做init.我应该抛出异常吗?我还有其他选择吗?
hyp*_*ypt 11
如果要覆盖标准-init方法,可以返回nil(如果您不想-init使用)或执行:
- (instancetype)init
{
return [self initWithObject:nil];
}
Run Code Online (Sandbox Code Playgroud)
如果要完全停止使用,-init可以将其标记为不可用属性或使用NSAssert:
// .h
// ...
- (instancetype)init UNAVAILABLE_ATTRIBUTE;
// ...
// .m
- (instancetype)init
{
NSAssert(NO, @"This method should not be used");
return nil;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用UNAVAILABLE_ATTRIBUTE或者NSAssert(),但是如果您使用UNAVAILABLE_ATTRIBUTE,则需要某种实现-init,即使它只是返回nil.
| 归档时间: |
|
| 查看次数: |
631 次 |
| 最近记录: |