开发者

objective C Iterate Method Call

How can I iterate a method call for example.

[self revertBox1];
[self revertBox2];
[self revertBox3];
[self revertBox4];
[self revertBox5];

// They are as many as 20.

example1 * xmp = [[example1 alloc] initWithNibName:@"example1" bundle:nil];

// How can I iterate the class instantiation example1, example2, example3

// If I use this method.. 

NSString *classNameStr = [NSString stringWithFormat:@"example%d", i];
Class cls开发者_C百科 = NSClassFromString(classNameStr);
cls *obj = [[[cls alloc] initWithNibName:classNameStr bundle:nil];

//I receive an error [ Use of undeclared identifier 'obj' ] 


You should rethink your design and approach to this...Instead of having 20 methods names -revertBoxN, how about make one method:

- (void)revertBox:(int)index { }

You would then have to replace your list of ivars (exampleN) with a C-array of a certain size.

You can use a terse loop to iterate through elements and avoid repetitive code.

Hopefully you can follow what I'm saying...I don't think I should have to go into more detail (otherwise you should learn the basics of Objective-C (that includes C!).


If you want to iterate the method calls,

for (int i=0; i<20; i++) {

    NSString *selectorNameStr = [NSString stringWithFormat:@"revertBox%d", i];
    SEL sel = NSSelectorFromString(selectorNameStr);
    [self performSelector:sel];
}

If you want to iterate the Class name, you can do like this,

for (int i=0; i<20; i++) {

    NSString *classNameStr = [NSString stringWithFormat:@"example%d", i];
    Class cls = NSClassFromString(classNameStr);
    cls *obj = [[[cls alloc] initWithNibName:classNameStr bundle:nil];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜