Simon Shi

放飞梦想,专注于Mobile开发

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: 订阅 订阅 :: 管理 ::

     无论在iPhone开发还是学习的过程中都会看到一些不是很理想的代码,不可否认自己也在不断“贡献”着这类代码。面对一些代码的“坏味道”,重构显然是 个有效的解决途径。《iPhone开发重构》系列就想总结和补充iPhone开发中经历的一些重构,其间可能会引用一些开源以及实际项目的代码,本着对技 术的探求,冒昧之处还请作者多多见谅。

    使用Objective-C的人应该都很熟悉通过alloc和init进行对象的“两阶段”创建。其实利用new的一次创建也是可以的,但由于“两阶段” 创建所具备的灵活性使得其成为了Objective-C创建对象的一种惯例。但真正使用的时候,开发人员有时更倾向与一些创建的辅助方法。比如 NSArray的arrayWithObjects以及arrayWithContentsOfFile等等。为此在类的接口设计时候考虑到友好性最好可 以提供一些更为简单的创建函数来封装“两阶段”的细节以及内存处理。借用下SoundEffect库的代码举例说明下:

重构前:

@implementation SoundEffect

// Initializes a sound effect object with the contents of the specified sound file
- (id)initWithContentsOfFile:(NSString *)path {
    self = [super init];
    // Gets the file located at the specified path.
    if (self != nil) {
        NSURL *aFileURL = [NSURL fileURLWithPath:path isDirectory:NO];
        // If the file exists, calls Core Audio to create a system sound ID.
        if (aFileURL != nil)  {
            SystemSoundID aSoundID;
            OSStatus error = AudioServicesCreateSystemSoundID((CFURLRef)aFileURL, &aSoundID);
            if (error == kAudioServicesNoError) { // success
                _soundID = aSoundID;
            } else {
                NSLog(@"Error %d loading sound at path: %@", error, path);
                [self release], self = nil;
            }
        } else {
            NSLog(@"NSURL is nil for path: %@", path);
            [self release], self = nil;
        }
    }
    return self;
}
@end

 

重构后:

@implementation SoundEffect

+ (id)soundEffectWithContentsOfFile:(NSString *)aPath {
    if (aPath) {
        return [[[SoundEffect alloc] initWithContentsOfFile:aPath] autorelease];
    }
    return nil;
}


- (id)initWithContentsOfFile:(NSString *)path {
   ……
}
@end

 

   其中,重构前的代码是我假想的,重构后的代码才是SoundEffect库现有的模样。经过重构后,SoundEffect类在创建时的友好性得到了很大的改善。

 

本文出自 “林家男孩” 博客,请务必保留此出处http://bj007.blog.51cto.com/1701577/545536

posted on 2011-11-30 16:48  Simon Shi  阅读(160)  评论(0编辑  收藏  举报