开发者

How to create generic id type properties?

开发者 https://www.devze.com 2023-02-05 16:53 出处:网络
I\'m new to iOS and Objective-C and trying to create a class that has a generic property. @interface HeaderInfo : NSObject {

I'm new to iOS and Objective-C and trying to create a class that has a generic property.

@interface HeaderInfo : NSObject { NSString *label; id value; }

@property (nonatomic, retain) NSString *label;
@property (nonatomic, retain) id value;
- (HeaderInfo *)init开发者_如何转开发WithLabel:(NSString *)lbl value:(id)val;

@end

Then I'm trying to add this class to an array:

[generalSection.items addObject:[[HeaderInfo alloc] initWithLabel:@"Tacho seal security" value:@"Some String Value"]];

[generalSection.items addObject:[[HeaderInfo alloc] initWithLabel:@"Tacho seal security" value:YES]];

but compiler doesn't like the 2nd addition and says:

Warning: passing argument 2 of 'initWithLabel:value:' makes pointer from integer without a cast

What I'm doing wrong? Any help is greatly appreciated.

And also how can check the value later on whether it's a BOOL or NSString?

Thanks.


The BOOL type is not a object, so you can't pass it as id (a generic object).

You should pass an NSNumber. An NSNumber is an object that encapsulate numbers when you want to pass a number as an object.

You can create a NSNumber like this : [NSNumber numberWithBool:YES];

You can retrieve the value with [value boolValue];

If you want to check the type of object you're having at runtime you can to it like that :

if ([value isKindOfClass:[NSNumber class]]) {
   //It's a number
}
else if ([value isKindOfClass:[NSString class]]) {
   //It's a string
}
0

精彩评论

暂无评论...
验证码 换一张
取 消