【问题标题】:Custom NSObject class, instantiate like [CustomObj customObjWithData:data] [duplicate]自定义 NSObject 类,实例化如 [CustomObj customObjWithData:data] [重复]
【发布时间】:2012-04-26 03:55:57
【问题描述】:

可能重复:
Class methods which create new instances

我想知道如何模拟 NSString、NSArray 等类的实例化:[NSArray arrayWithObject:object]... 希望消除初始化和分配。

我可能不熟悉它的实际作用。根据文档, [NSSArray array] 创建并返回一个空数组。这到底是什么意思,任何分配?

我希望能够拥有一个自定义 NSObject 类并执行以下操作:[CustomObj customObjWithData:data]

谢谢!

【问题讨论】:

  • 只返回一个自动释放的对象。如果您使用 ARC,只需返回 alloc/init 调用的结果即可。

标签: objective-c ios memory-management nsobject


【解决方案1】:

先写一个对应的自定义init...方法:

- (id)initWithFoo:(Foo *)aFoo
{
     // Do init stuff.
}

然后添加一个调用alloc 的自定义工厂方法和您的自定义init... 方法:

+ (id)customObjWithFoo:(Foo *)aFoo
{
    return [[[self alloc] initWithFoo:aFoo] autorelease];
}

如果使用 ARC 编译,请省略 autorelease 调用。

【讨论】:

    【解决方案2】:

    这些是类方法。通常,它们也有实例 init* 方法。比如……

    - (id)initWithData:(NSData*)data
    {
      // Call appropriate super class initializer
      if (self = [super init]) {
        // Initialize instance with the data
      }
      return self;
    }
    
    + (id)customObjWithData:(NSData*)data
    {
      return [[self alloc] initWithData:data];
    }
    

    现在,你可以称之为...

    CustomObj *obj = [CustomObj customObjWithData:data];
    

    【讨论】:

    • 除非在 ARC 下,构造函数应该在返回新对象之前发送autorelease
    • 是的,但就个人而言,我不喜欢在与该问题没有直接关系的帖子中看到所有关于内存管理的 cmets。人们应该知道他们的目标是什么内存管理模型,并适当地编码。如果他们已经了解内存管理,他们就已经知道此代码假定为 ARC。如果他们不这样做,那么现在他们可能正在使用 Xcode 的 ARC 版本。
    【解决方案3】:

    你需要做类似...

    + (CustomObj *)customObjWithData:(NSData *)data {
        return [[[CustomObj alloc] initWithData:data] autorelease];
    }
    

    ...并实现一个 initWithData: 来处理变量的初始化。

    【讨论】:

    • 总是从初始化器返回id;使用[self alloc] 而不是硬编码类名以正确支持子类化。
    【解决方案4】:

    这里的很多答案都是正确的。我总是通过 Storyboard-instantiation 创建一种方法来轻松地进行 alloc en 实例化:

    //FooViewController.m

    + (id)create
    {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Storyboard" bundle:nil];
    
        return [storyboard instantiateViewControllerWithIdentifier:@"FooViewController"];
    }
    
    + (UINavigationController *)createWithNavagionController
    {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Storyboard" bundle:nil];
    
        FooViewController *fooViewController = [storyboard instantiateViewControllerWithIdentifier:@"fooViewController"];
    
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:fooViewController];
    
        return navigationController;
    }
    

    如果您需要参数,请创建类方法,例如:createWithName:(NSString *)name

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-20
      • 2020-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2013-03-07
      相关资源
      最近更新 更多