根据this article目标C中的For循环可以使用IMP & IMP进行优化。我现在一直在想这个想法,今天我一直在尝试一些测试。 然而,似乎为一个班级工作,似乎并没有为另一个工作。此外,我想知道加速是如何发生的? 通过回避objC_mesgSent?目标C用于使用SEL和IMP进行环路优化
问题1 这是怎么回事:
Cell *cell;
for (NSMutableArray *row in self.data) {
for (Data *d in row){
cell = [[Cell alloc] initWithRect:tmp_frame];
[self addSubview:cell.view];
[self.cells addObject:cell];
比这更糟糕的
:
SEL addCellSel = @selector(addObject:);
IMP addCellImp = [self.cells methodForSelector:addCellSel];
Cell *cell;
for (NSMutableArray *row in self.data) {
for (Data *d in row){
cell = [[Cell alloc] initWithRect:tmp_frame];
[self addSubview:cell.view];
addCellImp(self.cells,addCellSel,cell);
问题2 为什么会失败? (注意自我是从UIView的继承的类)
SEL addViewSel = @selector(addSubview:);
IMP addViewImp = [self methodForSelector:addViewSel];
Cell *cell;
for (NSMutableArray *row in self.data) {
for (Data *d in row){
cell = [[Cell alloc] initWithRect:tmp_frame];
addViewImp(self,addViewSel,cell.view);
[self.cells addObject:cell];
错误:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[SimpleGridView addSubview:]: unrecognized selector sent to instance 0xaa3c400'
告诉我方法addSubview还没有在我的课“SimpleGridView”被发现。 但是,当我尝试:
if ([self respondsToSelector:addViewSel]){
NSLog(@"self respondsToSelector(AddViewSel)");
addViewImp(self,addViewSel,cell.view);
} else {
NSLog(@"self does not respond to selector (addViewSel");
[self addSubview:cell.view];
}
我仍然得到完全相同的错误!
问题3 为何无法设置一个选择器&实施一类初始化/新方法,像这样:
iContactsGridCell *cell;
SEL initCellSel = @selector(initWithRect:);
IMP initCellImp = [iContactsGridCell methodForSelector:initCellSel];
for (NSMutableArray *row in self.data) {
for (Data *d in row){
cell = initCellImp([iContactsGridCell new],initCellSel,tmp_frame);
参考: 类iContactsGridCell从类细胞继承,其定义和实施
- (id) initWithRect:(CGRect)frame;
此外,铸造没有帮助(约合无法识别的选择同样的错误)
iContactsGridCell *cell;
SEL initCellSel = @selector(initWithRect:);
IMP initCellImp = [Cell methodForSelector:initCellSel];
for (NSMutableArray *row in self.data) {
for (Data *d in row){
cell = (iContactsGridCell *)initCellImp([Cell new],initCellSel,tmp_frame);
尝试不同的组合,如:
IMP initCellImp = [Cell methodForSelector:initCellSel];
或者
cell = initCellImp([iContactsGridCell class],initCellSel,tmp_frame);
产生完全相同的错误。 所以,请告诉我,我错过了什么,这有什么好处,是否有可能为类初始化方法提供IMP/SEL? 此外,与此相比,C函数指针会更快吗,还是上面所有的只是一个Objective-C函数指针包装器? 谢谢! PS:我很抱歉,如果这些问题一次是太多的问题。
为什么不切换到纯C呢? –
@RamyAlZuhouri大会。或者手动编译原始机器码。 (严重:这是一个微型优化。) – 2012-12-21 18:35:32
为了记录,您应该在调用IMP之前将IMP投射到正确的函数原型。 –