I create an object of class in current class:
CustomTableViewController * dController = [[CustomTableViewController init] alloc];
[dController getItemsByCategory:@"3" andCategory:@"4"];
After this I get error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[CustomTableViewController<0x102b35298> init]: cannot init a class object.'
CustomTableViewController
is:
@implementation CustomTableViewController
- (instancetype)init
{
self = [super init];
if (self) {
// TODO
}
return self;
}
- (void) getItemsByCategory: (NSString*) id andCategory:(NSString*) category {
// TODO
}
}
Also I have declared function getItemsByCategory
in .h
file
答案 0 :(得分:1)
You're calling the methods in the wrong order here:
CustomTableViewController * dController = [[CustomTableViewController init] alloc]
Change to
CustomTableViewController * dController = [[CustomTableViewController alloc] init]
答案 1 :(得分:1)
However, I think it's worth knowing why what you're doing is fundamentally incorrect.
[root@data-03] Executing task 'echoing'
['root@data-03']
current host: root@data-03
[root@data-01] Executing task 'echoing'
['root@data-03']
current host: root@data-01
Done.
is a static method. It can only be called on a class, not an instance (alloc
not CustomTableViewController
). What it does is allocate the memory for your instance, and will return a new instance of your class.
CustomTableViewController *
is an instance method. It can only be called on an instance, not a class (init
not CustomTableViewController *
). What it does is initialise your instance, by performing basic setup, and will return that initialised instance.
Therefore, calling CustomTableViewController
on a class makes absolutely no sense fundamentally, as there's no memory to perform the initial setup in to begin with.
It's the programming equivalent of trying to put objects in a box, before the box exists.