Objective-C编码风格 - 类别而不是标记?

时间:2014-03-25 19:40:54

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

出于代码组织原因,将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

1 个答案:

答案 0 :(得分:3)

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

  

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

因此,您可以选择更直观的内容来管理代码。这里将 在运行时没有区别。