NSClassFromString - doesn't work
i'm trying to use dynamic typing in Obj-C, i've got follow开发者_运维百科ing code and errors:
For me it seems good, but it don't want to work, any ideas?
Because you're creating cellClass at runtime, the compiler doesn't know about it so it can't compile that code.
This would work :
Class cellClass = NSClassFromString(@"CustomCell");
UITableViewCell *cell; // You could just id here as well if you wanted but you now that CustomCell is definitely a type of UITableViewCell
cell = [tableView dequeueReusableCellWithIdentifier:@"rssItemCell"];
However, why don't you just do this?
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:@"rssItemCell"];
Since you are not actually creating a new instance (just retrieving one), there is no need for this. This is sufficient:
// If we don't know the exact class of the cell, type it with the common superclass of all cells
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"rssItemCell"];
You can't use your variable cellClass as a type, it's an object.
In this case you have to use an id object or UITableViewCell. Something like this :
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"rssItemCell"];
or
id cell = [tableView dequeueReusableCellWithIdentifier:@"rssItemCell"];
精彩评论