为什么MemberOfClass不起作用

时间:2014-12-19 14:34:49

标签: ios objective-c

我不清楚MemberOfClass是如何工作的。请查看以下示例。 为什么在下面的例子中lbl.textColor不是成员?请为我清楚。

    UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 100)];
    lbl.text = @"HI";
    lbl.textColor = [UIColor grayColor];
    [self.view addSubview:lbl];

    if ([lbl.textColor isMemberOfClass:[UIColor class]]) { // Why Not Memeber
        NSLog(@"Member");
    }else {
        NSLog(@"Not Member");
    }

    if ([lbl.text isMemberOfClass:[NSString class]]) {// Why Not Memeber
        NSLog(@"Member");
    }else {
        NSLog(@"Not Member");
    }
    if ([imgView.image isMemberOfClass:[UIImage class]]) {// Memeber
        NSLog(@"Member");
    }else {
        NSLog(@"Not Member");
    }

//输出

 2014-12-19 20:17:43.383 Demo[13720:70b] Not Member
 2014-12-19 20:17:45.883 Demo[13720:70b] Not Member
 2014-12-19 20:17:52.772 Demo[13720:70b] Member

2 个答案:

答案 0 :(得分:5)

您会发现在创建颜色后记录颜色的类别是显而易见的:

lbl.textColor = [UIColor grayColor];
NSLog(@"lbl.textColor class=%@", NSStringFromClass([lbl.textColor class]));

你可能会发现实际的课程是UIDeviceRGBColorUICachedDeviceGrayColor或其他类似的,这是因为class clustering

如果对象是指定类的成员,则isMemberOfClass仅返回YES,如果对象是成员,则isKindOfClass返回YES指定类或子类

编辑请注意,UIColor似乎不使用类群集,@ Popeye的答案中的点数有效。我的一般建议是永远不要在系统类上使用isMemberOfClass,然后你就不必担心类集群了。

答案 1 :(得分:2)

第一个if statement始终为Not Memeber,因为您NSLog(@"Not Memeber");两个出来都是TRUE。第一个将返回lbl.textColor,因为UIColor将返回isMemberOfClass:的实例,而"isMemberOfClass: Returns a Boolean value that indicates whether the receiver is an instance of a given class"的工作方式与TRUE相同,取自Apple Documentation for NSObject }。同样取自Apple Docs,同样重新强制该行应返回"Class objects may be compiler-created objects but they still support the concept of membership. Thus, you can use this method to verify that the receiver is a specific Class object."textColor,此处您正在检查从UIColor返回的类是否为{{1}的特定类1}}

if ([lbl.textColor isMemberOfClass:[UIColor class]]) { //  Not Memeber
    NSLog(@"Not Memeber"); // This one is actually returned.
}else {
    NSLog(@"Not Memeber");
}

第二个将始终为Not Memember,因为lbl.text会返回NSString a UILabel

if ([lbl.text isMemberOfClass:[UILabel class]]) {//Not Memeber
    NSLog(@"Memeber");
}else {
    NSLog(@"Not Memeber"); // Correctly being return 
}

第3个正确返回Memeber,因为imgView.image返回UIImage

if ([imgView.image isMemberOfClass:[UIImage class]]) {// Memeber
    NSLog(@"Memeber"); // Correctly being returned
}else {
    NSLog(@"Not Memeber");
}

它的拼写Member不是Memeber

修改

我刚刚NSLog(@"lbl.textColor class=%@", NSStringFromClass([lbl.textColor class]));根据Droppy回答建议我做lbl.textColor class=UIColor所以这再次说它应该为if statement