Reputation: 1775
Hello dear programmers,
I have a requirement for creating a custom tableviewcell with a method below:
@interface CustomTableCell : UITableViewCell {
}
@implementation CustomTableCell
-(void)setObjectWithType:(NSString *)objectType atPlace:(CGRect) placeOfObject
{
class className=NSClassFromString(objectType);
className *objectName = [[NSClassFromString(objectType) alloc] init];// Giving error
}
Please solve this issue to create any type of object by passing the arguments like below:
CustomTableCell *cell=[[CustomTableCell alloc] init];
[cell setObjectWithType:@"UILabel" atPlace:CGRectMake(0, 0, 100, 30)];
Thanks, in advance.
Upvotes: 2
Views: 282
Reputation: 119242
This sounds like it could turn into a nightmare down the line, but to solve your immediate problem, you'd have to use id
or the lowest common superclass (e.g. UIView
) when creating your arbitrary objects:
id objectName = [[NSClassFromString....
The compiler can't cast dynamically the way you are attempting. It has to be done at runtime.
Upvotes: 1
Reputation: 29767
Use common type like id
:
id objectName = [[NSClassFromString(objectType) alloc] init];
You can also use UIView, NSObject. depends of your purposes
Upvotes: 0