【问题标题】:Objective-C Coding Style - Categories instead of Marks?Objective-C 编码风格 - 类别而不是标记?
【发布时间】:2014-03-25 19:40:54
【问题描述】:

出于代码组织的原因,将 Objective-C 类的实现分为几类是否有不利之处。而不是使用传统的#pragma mark - SectionTitle方式?

下面我包含了单个实现文件的一部分的对比示例。

分类方法

@implementation Gallery

+ (NSArray*)titles
{
  return @[@"St. Augustine", @"Roanoke", @"Jamestown", @"Santa Fe"];
}

@end

@implementation Gallery (Overrides)

- (NSString*)description
{
  return self.title;
}

- (NSString*)debugDescription
{
  return [NSString stringWithFormat:@"%@ - %u items",
          self.title, (unsigned int)[self.items count]];
}

@end

@implementation Gallery (Debug)

+ (instancetype) randomGalleryWithTitle:(NSString*)title;
{
  Gallery *gallery = [[Gallery alloc] init];

  gallery.title = title;
  gallery.iconImageName = title;

  NSMutableArray *items = [NSMutableArray array];
  for (int i = 0; i < 20; ++i) {

    if(rand() % 2 == 0) {
      ArtObject *randomArtObject = [ArtObject randomArtObject];
      randomArtObject.galleryTitle = gallery.title;
      [items addObject:randomArtObject];
    } else {
      Story *randomStory = [Story randomStory];
      randomStory.galleryTitle = gallery.title;
      [items addObject:randomStory];
    }
  }

  gallery.items = items;

  return gallery;
}

@end

常规方法

@implementation Gallery

+ (NSArray*)titles
{
  return @[@"St. Augustine", @"Roanoke", @"Jamestown", @"Santa Fe"];
}

@end

#pragma mark - Overrides

- (NSString*)description
{
  return self.title;
}

- (NSString*)debugDescription
{
  return [NSString stringWithFormat:@"%@ - %u items",
          self.title, (unsigned int)[self.items count]];
}

@end

#pragma mark - Debug

+ (instancetype) randomGalleryWithTitle:(NSString*)title;
{
  Gallery *gallery = [[Gallery alloc] init];

  gallery.title = title;
  gallery.iconImageName = title;

  NSMutableArray *items = [NSMutableArray array];
  for (int i = 0; i < 20; ++i) {

    if(rand() % 2 == 0) {
      ArtObject *randomArtObject = [ArtObject randomArtObject];
      randomArtObject.galleryTitle = gallery.title;
      [items addObject:randomArtObject];
    } else {
      Story *randomStory = [Story randomStory];
      randomStory.galleryTitle = gallery.title;
      [items addObject:randomStory];
    }
  }

  gallery.items = items;

  return gallery;
}

@end

【问题讨论】:

    标签: objective-c coding-style objective-c-category


    【解决方案1】:

    来自"Customizing Existing Classes" 在“使用 Objective-C 编程”指南中:

    在运行时,类别添加的方法之间没有区别 和一个由原始类实现的。

    因此,您可以选择任何您认为更直观的方式来管理您的代码。这里将 在运行时没有区别。

    【讨论】:

    • 感谢您的回答。我应该回头看看指南。
    • 此外,如果它们都在同一个可执行文件中实现,链接器会将一个类别与其类合并。这意味着运行时开销为零——该类别在运行时甚至没有独立的标识。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    • 2010-12-17
    • 2010-11-15
    相关资源
    最近更新 更多