代码之家  ›  专栏  ›  技术社区  ›  pjb3

如何在Objective-C中创建分配器类方法?

  •  1
  • pjb3  · 技术社区  · 16 年前

    我有一个班,有酒吧。我希望有一个类方法来获取具有bar属性集的nsfoo实例。这类似于nsstring StringWithFormat类方法。所以签名是:

    + (NSFoo *) fooWithBar:(NSString *)theBar;
    

    所以我这样称呼它:

    NSFoo *foo = [NSFoo fooWithBar: @"bar"];
    

    我想这可能是正确的:

    + (NSFoo *) fooWithBar:(NSString *)theBar {
      NSFoo *foo = [[NSFoo alloc] init];
      foo.bar = theBar;
      [foo autorelease];
      return foo;  
    }
    

    看起来对吗?

    2 回复  |  直到 16 年前
        1
  •  2
  •   Barry Wark    16 年前

    是的,您的实现看起来是正确的。因为 -[NSObject autorelease] 收益率 self ,您可以将返回语句编写为 return [foo autorelease] .有些人建议在分配时自动释放一个对象,如果您要使用自动释放(而不是释放),因为它使意图变得清晰,并将所有内存管理代码保持在一个位置。你的方法可以写成:

    + (NSFoo *) fooWithBar:(NSString *)theBar {
      NSFoo *foo = [[[NSFoo alloc] init] autorelease];
      foo.bar = theBar;
    
      return foo;  
    }
    

    当然,如果 -[NSFoo initWithBar:] 存在,您可能会将此方法编写为

    + (NSFoo *) fooWithBar:(NSString *)theBar {
      NSFoo *foo = [[[NSFoo alloc] initWithBar:theBar] autorelease];
    
      return foo;  
    }
    
        2
  •  2
  •   James Eichele Bernard Igiri    16 年前

    对。看起来不错。而您的实现似乎是一种常见的实践。