开发者

Objective C tip?

I want to replace this:

self.fajerImage     = [UIImage imageNamed:@"FirstViewBG_5N.png"];
self.shrogImage     = [UIImage imageNamed:@"FirstViewBG_4N.png"];
self.dohorImage     = [UIImage imageNamed:@"FirstViewBG_3N.png"];
self.aaserImage     = [UIImage imageNamed:@"FirstViewBG_2N.png"];
self.mgribImage     = [UIImage imageNamed:@"FirstViewBG_1N.png"];
self.eeshaImage     = [UIImage imageNamed:@"F开发者_如何学编程irstViewBG_0N.png"];

With a for loop.. I don't know how to call the ivars one after another in a loop..

Please note that putting them in an array before the loop is a great idea that I have not been successful in implementing..

Thanks!


One great way to do this involves key value coding, as discussed in this blog post. Try using:

NSArray *nameArray = [[NSArray alloc] initWithObjects:@"fajerImage",
                                                     @"shrogImage",
                                                     @"dohorImage",
                                                     @"aaserImage",
                                                     @"mgribImage",
                                                     @"eeshaImage",
                                                     nil];

int i = 0;
for (NSString *name in nameArray) {
    UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"FirstViewBG_%dN.png", i++]];
    [self setValue:image forKey:name];
}

[nameArray release];

(You should replace UIImage in my code above with the actual object type, if I've gotten it wrong.)


You could use Key Value Coding syntax:

NSString *names=[NSArray arrayWithObjects:@"eeshaImage",@"mgribImage",@"aaserImage",@"dohorImage",...,nil];

for (int i=0; i<names.count; i++) {
      NSString *name=[names objectAtIndex:i];
      UIImage *image=[UIImage imageNamed:[NSString stringWithFormat:@"FirstViewBG_%dN.png",i
      [self setValue:image forKey:name];
 }


A coworker of mine is fond of a pattern like the following (untested):

 id *images[] = {
    &eeshaImage,
    &mgribImage,
    &aaserImage,
    &dohorImage,
    &shrogImage,
    &fajerImage
 };

 for (size_t i = 0;i < sizeof(images) / sizeof(*images);++i) {
    NSString *name = [NSString stringWithFormat:@"FirstViewBG_%zuN.png", i];
    *(images[i]) = [[UIImage imageNamed:name] retain];
 }

You have to ask yourself if the cost in readability is worth it just to make it a tiny bit more extensible, though.


Another thing you can do that is usually fast enough is allocate your images on demand rather than try and initialize them all at once. Name them something like "FirstViewBG_Fajer.png" and then write an instance method like:

- (UIImage *) imageNamed:(NSString *) name {
    return [UIImage imageNamed: [NSString stringWithFormat:
    @"FirstViewBG_%@.png", name]];
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜