简体   繁体   中英

UILabel Subclass appears as UILabel in Objective-C

I'm a experienced C++ programmer trying to create my first Objective-C subclass of UILabel with an added read-only property

// UINumericlabel.h
@interface UINumericLabel : UILabel

// Returns true if the numeric display contains a decimal point
@property (readonly,nonatomic) BOOL hasDecimalPoint;
@end

//  UINumericLabel.m

#import "UINumericLabel.h"

@implementation UINumericLabel
// Returns true if the numeric display contains a decimal point
- (BOOL) hasDecimalPoint;
{
   return [self.text rangeOfString:(@".")].location != NSNotFound;
}
@end

When I try to reference the hasDecimalPoint property for an instantiated UINumericLabel I get an abort with error 2012-02-20 18:25:56.289 Calculator[10380:207] -[UILabel hasDecimalPoint]: unrecognized selector sent to instance 0x684c5c0

In the debugger it shows my declaration of a UINumericLabel property as being a UILabel * Do I need to override the (id)init for UILabel in my UINumericLabel subclass? How do I do that?

#import "UINumericLabel.h"

@interface CalculatorViewController : UIViewController <ADBannerViewDelegate>
@property (weak, nonatomic) IBOutlet UINumericLabel *display0;
@end

When I hover over display0P in the debugger it says it is a UILabel * not a UINumericLabel *

UINumericLabel * display0P = self.display0;

In the Interface Builder select the label and then open the Identity Inspector. In the text field "Class" it probably says UILabel . Change that to be your new subclass, UINumericLabel .

I agree with @Brian above, but would add two things: (1) no need for a declared property unless you plan to cache the BOOL value. Just use a method with a predeclaration in .h, and (2) no need for a subclass in this case. A better approach would be an extension, like: UILabel+JonN.h...

@interface UILabel (JonN)

-(BOOL)hasDecimal;

@end

Then, in UILabel+JonN.m...

@implementation UILabel (JonN)

// your method as written

@end

This is prettier, I think, and solves the problem you were having with IB (which I think @Brian correctly addressed).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM