开发小技巧

Objective-C分析之二

2017-10-17  本文已影响6人  MrSong

发送消息(Sending Messages)

消息转发(Forwarding Messages)

动态执行(Dynamically Resolving Methods)

错误处理(Error Handling)

归档(Archiving)

对象方法(Instance Methods)

    NSDictionary *temp1 = @{@"1":@"111",@"2":@"2222",@"3":@"333"};
    NSDictionary *temp2 = [temp1 dictionaryWithValuesForKeys:@[@"1",@"4"]];
    NSLog(@"temp2",temp2);
- (void)viewDidLoad {
    [super viewDidLoad];
    self.label = [UILabel new];
    [self.label addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:@"text"];
    self.label.text = @"111";
    self.label.text = @"333";
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    NSLog(@"%@",change);
    /*
     // 第一次拿到的old是null,如果用的话要注意判断
     {
     kind = 1;
     new = 111;
     old = "<null>";
     }
     
     {
     kind = 1;
     new = 333;
     old = 111;
     }
     */
}
    self.label = [UILabel new];
    [self.label setValue:@"ddddd" forKey:@"text"];//self.label.text = @"dddd";
    NSLog(@"text:%@",self.label.text);
    [self setValue:@"eeee" forKeyPath:@"self.label.text"];
    NSLog(@"text:%@",self.label.text);
 - (void)viewDidLoad {
    [super viewDidLoad];
    
    // 这样随便写都不会闪退
    [self setValue:@"dddd" forUndefinedKey:@"ddddd"];
 }

// 这样重写一下就好
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
    
}
    NSDictionary *temp = @{@"text":@"ddddddddddddddd",@"title":@"song"};
    [self setValuesForKeysWithDictionary:temp];
    NSLog(@"title:%@",self.title);
   self.label.text = @"1234567890-=";
    self.title = @"song"
    NSLog(@"title:%@",[self valueForKey:@"title"]);
    NSLog(@"text:%@",[self valueForKeyPath:@"self.label.text"]);

类型方法(Type Methods)

NSObject相关方法到这里就完了,接下来看一下Object对象

Protocol NSObject

    NSLog(@"self class %@",[self class]);
    NSLog(@"self superclass %@",[self superclass]);
    NSLog(@"self isEqual %zd",[self.label isEqual:lab]);
    NSLog(@"self hash %zd - label %zd",self.hash,self.label.hash);
    NSLog(@"self self %@",self);
    
    // 这个会比较父类
    NSLog(@"self isKindOfClass %zd",[self.label isKindOfClass:[UIView class]]);
    NSLog(@"self isKindOfClass %zd",[self.label isKindOfClass:[UILabel class]]);
    NSLog(@"self isKindOfClass %zd",[self.label isKindOfClass:[UIButton class]]);
    
    // 这个精准比较当前类
    NSLog(@"self isMemberOfClass %zd",[self.label isMemberOfClass:[UILabel class]]);
    NSLog(@"self isMemberOfClass %zd",[self.label isMemberOfClass:[UIButton class]]);
    NSLog(@"self isMemberOfClass %zd",[self.label isMemberOfClass:[UIViewController class]]);
    
    NSLog(@"self conformsToProtocol %zd",[self conformsToProtocol:@protocol(NSObject)]);
    
    NSLog(@"self description %@",self.description);
    NSLog(@"self isProxy %zd",[self isProxy]);
    NSLog(@"self.label isProxy %zd",[self.label isProxy]);
上一篇 下一篇

猜你喜欢

热点阅读