この記事によると、Objective CのForループは、SELとIMPを使用して最適化できます。私は少し前からこのアイデアをいじっていましたが、今日はいくつかのテストを試しています。ただし、あるクラスでは機能しているように見えますが、別のクラスでは機能していないようです。さらに、スピードアップがどのように正確に発生するのか知りたいですか?objC_mesgSentを回避することによって?
質問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 なぜこれが失敗するのですか?(selfは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];
エラー:
キャッチされなかった例外'NSInvalidArgumentException'が原因でアプリを終了しています、理由:'-[SimpleGridView addSubview:]:認識されないセレクターがインスタンス0xaa3c400に送信されました'
クラス"SimpleGridView"にメソッドaddSubviewが見つからないことを教えてくれます。しかし、私が試したとき:
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 セレクターと実装を次のようにClassInit/newメソッドに設定できないのはなぜですか。
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は、クラスCellを継承します。これは、クラスCellを定義し、実装します。
- (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);
まったく同じエラーを生成します。では、何が欠けているのか、これはどのように有益であり、クラスinitメソッドにIMP / SELを使用することは可能ですか?また、C関数ポインターはこれに比べて高速ですか、それとも上記のすべてが単にObjective-C関数ポインターラッパーですか?ありがとうございました !PS:一度に質問が多すぎる場合は、お詫び申し上げます。