【发布时间】: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