iOS Developer

Effective Objective-C读后笔记(2)

2017-06-20  本文已影响11人  dispath_once

11、runtime消息转发机制


12、runtime的方法交换&便利归档和解档

  + (void)swizzlingInClass:(Class)cls originalSelector:(SEL)originalSelector swizzledSelector:(SEL)swizzledSelector {
    Class clzz = cls;
    Method originalMethod = class_getInstanceMethod(clzz, originalSelector);
    Method swizzMethod = class_getInstanceMethod(clzz, swizzledSelector);
    BOOL didAddMethod = class_addMethod(clzz, originalSelector, method_getImplementation(swizzMethod), method_getTypeEncoding(swizzMethod));
    if (didAddMethod) {
        NSLog(@"replace方法成功");
        class_replaceMethod(clzz, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    }
    else {
        NSLog(@"交换方法成功");
        method_exchangeImplementations(originalMethod, swizzMethod);
    }
}
 - (void)encodeWithCoder:(NSCoder *)aCoder {
   unsigned int count = 0;
   Ivar *ivars = class_copyIvarList([People class], &count);
   for (NSUInteger i = 0; i < count; i ++) {
       Ivar ivar = ivars[i];
       const char *name = ivar_getName(ivar);
       NSString *key = [NSString stringWithUTF8String:name];
       id value = [self valueForKey:key];
       [aCoder encodeObject:value forKey:key];
   }
   free(ivars);
}
 - (id)initWithCoder:(NSCoder *)aDecoder {
   self = [super init];
   if (self) {
       unsigned int count = 0;
       Ivar *ivars = class_copyIvarList([People class], &count);
       for (NSUInteger i = 0; i < count; i ++) {
           Ivar ivar = ivars[i];
           const char *name = ivar_getName(ivar);
           NSString *key = [NSString stringWithUTF8String:name];
           id value = [aDecoder decodeObjectForKey:key];
           [self setValue:value forKey:key];
       }
       free(ivars);
   }
   return self;
}

13、为自己创建的类提供全能初始化方法


14、尽可能的实现description方法


15、对象尽量为不可变


16、Objective-C里面的错误处理


17、NSCopying协议的理解


18、Objective-C里面的委托


19、“大类”通过分类的方式进行切割


20、第三方分类的管理

上一篇 下一篇

猜你喜欢

热点阅读