在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
网上看到的 http://esoftmobile.com/2013/08/10/effective-objective-c/
Chapter 1: Accustoming Yourself to Objective-CItem 1: Familiarize Yourself with Objective-C's RootsItem 2: Minimize Importing Headers in Headers减少头文件中引入( Item 3: Prefer Literal Syntax over the Equivalent Methods尽可能使用对象字面量的形式来创建或操作基础对象(NSString、NSNumber、NSArray、NSDictionary等),这种形式不仅使用方便,代码看起来也更清晰。 NSString *someString = @"Effective Objective-C"; NSNumber *someNumber = @1; NSNumber *intNumber = @10; NSNumber *floatNumber = @2.5f NSNumber *doubleNumber = @3.14159; NSNumber *boolNumber = @YES; NSNumber *charNumber = @'a'; NSArray *array = @[ object1, object2, object3 ]; NSDictionary *dict = @{ @"name": @"TracyYih", @"blog": @"http://esoftmobile.com" }; NSMutableArray *mutableArray = [@[ object1, object2 ] mutableCopy]; mutableArray[2] = object3; NSMutableDictionary *mutableDict = [@{ @"name": @"TracyYih" } mutableCopy]; mutableDict[@"age"] = @25; Item 4: Prefer Typed Constants to Preprocessor #define尽量用类型化的常量来代替使用 //In head file. extern const NSTimeInterval EOCAnimatedViewAnimationDuration; extern NSString *const EOCLoginManagerDidLoginNotification; //In implmentation file. const NSTimeInterval EOCAnimatedViewAnimationDuration = 0.3; NSString *const EOCLoginManagerDidLoginNotification = @"EOCLoginManagerDidLoginNotification"; Item 5: Use Enumerations for States, Options, and Status Codes使用枚举来表示各种状态,选项。其中申明枚举类型推荐使用Apple的 typedef NS_ENUM(NSUInteger, EOCConnectionState) { EOCConnectionStateDisconnected, EOCConnectionStateConnecting, EOCConnectionStateConnected, }; switch (_currentState) { case EOCConnectionStateDisconnected: break; case EOCConnectionStateConnecting: break; case EOCConnectionStateConnected: break; } 使用枚举表示状态使代码的可读性大大增强,对比下面的代码你就知道了: switch (_currentState) { case 0: break; case 1: break; case 2: break; } Chapter 2: Objects, Messaging, and the RuntimeItem 6: Understand Properties《Ry’s Objective-C Tutorial》# Properties Item 7: Access Instance Variables Primarily Directly When Accessing Them InternallyItem 8: Understand Object Equality在自定义类中,我们可以通过实现 Item 9: Use the Class Cluster Pattern to Hide Implementation Detail必要时通过工厂模式来隐藏一些实现的细节。 @implementation Employee + (Employee *)employeeWithType:(EmployeeType)type { switch (type) { case EmployeeTypeDeveloper: return [[EmployeeDeveloper alloc] init]; break; case EmployeeTypeDesigner: return [[EmployeeDesigner alloc] init]; break; case EmployeeTypeFinance: return [[EmployeeFinance alloc] init]; break; } } @end Item 10: Use Associated Objects to Attach Custom Data to Existing Classes代码内容与该主题看不出来关联,先说主题吧,应该是必要时使用 代码部分是可以通过函数指针来延迟函数的绑定。 void printHello() { printf("Hello, world!\n"); } void printGoodbye() { printf("Goodbye, world!\n"); } void doTheThing(int type) { void (*fnc)(); //here. if (type == 0) { fnc = printHello; } else { fnc = printGoodbye; } fnc(); return 0; } Item 11: Understand the Role of objc_msgSend该主题没有对应代码,详见 《Objective-C Runtime Programming Guide》。 Item 12: Understand Message Forwarding必要时我们可以通过实现 + (BOOL)resolveInstanceMethod:(SEL)selector { NSString *selectorString = NSStringFromSelector(selector); if (/* selector is from a @dynamic property */) { if ([selectorString hasPrefix:@"set"]) { class_addMethod(self, selector, (IMP)autoDictionarySetter, "v@:@"); } else { class_addMethod(self, selector, (IMP)autoDictionaryGetter, "@@:"); } return YES; } return [super resolveInstanceMethod:selector]; } Item 13: Consider Method Swizzling to Debug Opaque Methods我们可以通过runtime提供的 // Exchanging methods Method originalMethod = class_getInstanceMethod([NSString class], @selector(lowercaseString)); Method swappedMethod = class_getInstanceMethod([NSString class], @selector(uppercaseString)); method_exchangeImplementations(originalMethod, swappedMethod); 这里例子比较有意思,实现了以上代码后,你再使用 Item 14: Understand What a Class Object Is借助于Objective-C强大的runtime系统,我们可以在代码中判断一个对象是属于什么类型。 // Class hierarchy checking NSMutableDictionary *dict = [NSMutableDictionary new]; [dict isMemberOfClass:[NSDictionary class]]; ///< NO [dict isMemberOfClass:[NSMutableDictionary class]]; ///< YES [dict isKindOfClass:[NSDictionary class]]; ///< YES [dict isKindOfClass:[NSArray class]]; ///< NO Chapter 3: Interface and API DesignItem 15: Use Prefix Names to Avoid Namespace Clashes在类名(Class)、协议名(Protocal)、分类名(Category)等加上自己的前缀避免与其他库或代码发生命名冲突。 Item 16: Have a Designated Initializer初始化方法是一个类的入口,所以我们需要精心的设计(其实每个方法都得用心设计),我个人习惯初始化方法中一般不会超过两个参数,尽量让初始化方法更简单,同时我们也需要照顾到继承来的初始化方法: // Designated initialiser - (id)initWithWidth:(float)width andHeight:(float)height { if ((self = [super init])) { _width = width; _height = height; } return self; } // Super-class’s designated initialiser - (id)init { return [self initWithWidth:5.0f andHeight:10.0f]; } // Initialiser from NSCoding - (id)initWithCoder:(NSCoder*)decoder { // Call through to super’s designated initialiser if ((self = [super init])) { _width = [decoder decodeFloatForKey:@"width"]; _height = [decoder decodeFloatForKey:@"height"]; } return self; } Item 17: Implement the description Method我们可以在自己的类中实现 @implementation EOCPerson ... // Description method for EOCPerson - (NSString*)description { return [NSString stringWithFormat:@"<%@: %p, \"%@ %@\">", [self class], self, _firstName, _lastName]; } ... @end Item 18: Prefer Immutable Objects很多情况下我们申明一个属性只是为了让外部能够获取一些信息(get),并不需要对这些信息作修改(set),所以这种情况下最好不要让外部能够修改,我们可以在申明该属性时加上 Item 19: Use Clear and Consistent Naming该部分应该讲的Objective-C编码规范,这里推荐Apple的《Coding Guidelines for Cocoa》。 Item 20: Prefix Private Method Names该部分建议给“私有方法”(只在当前类的实现文件中使用的方法)加上前缀以便和其他方法区分开,这里建议的命名形式为: Item 21: Understand the Objective-C Error Model在Objective-C中,错误处理可以有两种形式:NSException 和 NSError 。 // Throwing exception id someResource = …; if ( /* check for error */ ) { @throw [NSException exceptionWithName:@"ExceptionName" reason:@"There was an error" userInfo:nil]; } [someResource doSomething]; [someResource release]; // Returning the error - (BOOL)doSomethingError:(NSError**)error { // Do something NSError *returnError = nil; if (/* there was an error */) { if (error) { *error = [NSError errorWithDomain:domain code:code userInfo:userInfo]; } return YES; } else { return NO; } } 其实在Objective-C中后一种更常见,我们可以结合前面提到的使用枚举类表示一些错误码类型。 typedef NS_ENUM(NSUInteger, EOCError) { EOCErrorUnknown = −1, EOCErrorInternalInconsistency = 100, EOCErrorGeneralFault = 105, EOCErrorBadInput = 500, }; Item 22: Understand the NSCopying Protocol我们知道大部分系统的类(UI & NS)可以调用 //Support the NSCopying protocol. @interface EOCPerson : NSObject <NSCopying> @end @implementation EOCPerson // NSCopying implementation - (id)copyWithZone:(NSZone*)zone { Person *copy = [[[self class] allocWithZone:zone] initWithFirstName:_firstName andLastName:_lastName]; return copy; } @end 我们也可以在该方法中控制是深拷贝还是浅拷贝,区别就是是否将当前对象的所有信息(所有成员变量)赋给拷贝后的对象。 Chapter 4: Protocols and CategoriesItem 23: Use Delegate and Data Source Protocols for Interobject Communication《Ry’s Objective-C Tutorial》# Protocols Item 24: Use Categories to Break Class Implementations into Manageable Segments当我们要实现一个功能丰富的类时,我们可以使用分类(Category)将该类分割成相对独立一些的块,这样代码结构会比所有东西都放在一起实现要清晰的多。 //RenderObject.h @class CXMLNode; @interface RenderObject : NSObject @property (nonatomic, copy, readonly) NSString *name; @property (nonatomic, weak, readonly) CXMLNode *node; @property (nonatomic, strong, readonly) UIView *view; @property (nonatomic, strong, readonly) NSDictionary *style; - (instancetype)initWithNode:(CXMLNode *)node style:(NSDictionary *)style; //... @end //RenderObject+RenderTree.h @interface RenderObject (RenderTree) @property (nonatomic, weak, readonly) RenderObject *parent; @property (nonatomic, weak, readonly) RenderObject *firstChild; @property (nonatomic, weak, readonly) RenderObject *lastChild; @property (nonatomic, weak, readonly) RenderObject *nextSibling; @property (nonatomic, weak, readonly) RenderObject *previousSibling; @end //RenderObject+Layout.h @interface RenderObject (Layout) - (void)layout; - (void)loadView; - (void)paint; //... @end
Item 25: Always Prefix Category Names on Third-Party Classes这个感觉与之前(Item 15)内容相似,给自己创建的所有分类(不管是基于Cocoa类还是第三方类)加上自己的前缀。 // Namespacing the category @interface NSString (ABC_HTTP) // Encode a string with URL encoding - (NSString*)abc_urlEncodedString; // Decode a URL encoded string - (NSString*)abc_urlDecodedString; @end Item 26: Avoid Properties in CategoriesObjective-C分类中是不允许增加成员变量的(Instance variables may not be placed in categories),我们可以通过运行时函数 //EOCPerson+FriendShip.h @interface EOCPerson (FriendShip) @property (nonatomic, strong) NSArray *friends; @end //EOCPerson+FriendShip.m static const char* kFriendsPropertyKey = "kFriendsPropertyKey"; @implementation EOCPerson (Friendship) - (NSArray*)friends { return objc_getAssociatedObject(self, kFriendsPropertyKey); } - (void)setFriends:(NSArray*)friends { objc_setAssociatedObject(self, kFriendsPropertyKey, friends, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } @end Item 27: Use the Class-Continuation Category to Hide Implementation Detail我们可以在实现文件中利用拓展(Class Extension)将不需要外界了解的成员变量移到拓展中,也就是所有我们应该在头文件中申明为 //EOCClass.h @class EOCSuperSecretClass @interface EOCClass : NSObject { @private EOCSuperSecretClass *_secretInstance; } @end 其中 //EOCClass.h @interface EOCClass : NSObject @end // EOCClass.m #import "EOCClass.h" #import "EOCSuperSecretClass.h" @interface EOCClass () { EOCSuperSecretClass *_secretInstance; } @end @implementation EOCClass // Methods here @end 在新版本编译器中,实现( @implementation EOCClass { EOCSuperSecretClass *_secretInstance; } // Methods here @end Item 28: Use a Protocol to Provide Anonymous Objects我们可以通过协议来提供匿名对象来调用一些方法或获取一些信息。 // Database connection protocol @protocol EOCDatabaseConnection - (void)connect; - (void)disconnect; - (BOOL)isConnected; - (NSArray*)performQuery:(NSString*)query; @end // Database manager class #import <Foundation/Foundation.h> @protocol EOCDatabaseConnection; @interface EOCDatabaseManager : NSObject + (id)sharedInstance; - (id<EOCDatabaseConnection>)connectionWithIdentifier:(NSString*)identifier; @end 这种用法在CoreData中也可以遇到: // Fetched results controller with section info NSFetchedResultsController *controller = /* some controller */; NSUInteger section = /* section index to query */; NSArray *sections = controller.sections; id <NSFetchedResultsSectionInfo> sectionInfo = sections[section]; NSUInteger numberOfObjects = sectionInfo.numberOfObjects; Chapter 5: Memory ManagementItem 29: Understand Reference Counting《Ry’s Objective-C Tutorial》#Memory Management Item 30: Use ARC to Make Reference Counting Easier《Ry’s Objective-C Tutorial》#Memory Management Item 31: Release References and Clean Up Observation State Only in dealloc在ARC模式下,dealloc方法中一般只应该出现两种操作:释放非Cocoa对象和移除观察者。 // Releasing CF objects and removing observer in `dealloc' - (void)dealloc { CFRelease(coreFoundationObject); [[NSNotificationCenter defaultCenter] removeObserver:self]; } Item 32: Beware of Memory Management with Exception-Safe Code在MRR(Manual Retain Release)下,需要特别留意异常情况下的内存管理问题。 // @try/@catch block under manual reference counting @try { EOCSomeClass *object = [[EOCSomeClass alloc] init]; [object doSomethingThatMayThrow]; [object release]; } @catch (...) { NSLog(@"Whoops, there was an error. Oh well, it wasn’t important."); } // Fixing the potential leak EOCSomeClass *object; @try { object = [[EOCSomeClass alloc] init]; [object doSomethingThatMayThrow]; } @catch (...) { NSLog(@"Whoops, there was an error. Oh well, it wasn’t important."); } @finally { [object release]; } 其实同样需要注意的还有在switch-case或if-else条件下,避免return前必要的对象没释放问题。 Item 33: Use Weak References to Avoid Retain CyclesItem 34: Use Autorelease Pool Blocks to Reduce High-Memory Waterline// Reducing high memory waterline with appropriately places @autoreleasepool NSArray *databaseRecords = …; NSMutableArray *people = [NSMutableArray new]; for (NSDictionary *record in databaseRecords) { @autoreleasepool { EOCPerson *person = [[EOCPerson alloc] initWithRecord:record]; [people addObject:person]; } } Item 35: Use Zombies to Help Debug Memory-Management ProblemsItem 36: Avoid Using retainCount// Never do this while ([object retainCount]) { [object release]; } |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论