1

可以说我有一些我想重复多次的代码。我应该如何最好地将它包含在我的 iPhone 应用程序中,只需要编写一次?

它是一个典型的 TableView 控制器应用程序。

//Set Icon
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(30,25,20,20)];
        imgView.image = [UIImage imageNamed:@"ico-date.png"];
        [self.view addSubview:imgView];

问候

4

2 回答 2

4

您的选择:

1)创建一个静态C函数来做

static UIImageView* myfunc(CGFloat x, CGFloat y, CGFloat w, CGFloat h,
  NSString* name, NSString* type, UIView* parent) {
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:
      CGRectMake(x,y,w,h)]; 
    imgView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]
      pathForResource:name ofType:type]];
    [self.view addSubView:imgView];
    [imgView release];
    return imgView;
}

2) 创建一个 C 宏

#define CREATE_ICON_VIEW(parent,x,y,w,h,name) \
  ...

3)创建一个Objective-C静态方法

// in @interface section
+ (UIImageView*)addIconWithRect:(CGRect)rect name:(NSString*)name
  type:(NSString*)type toView:(UIView*)view;

// in @implementation section
+ (UIImageView*)addIconWithRect:(CGRect)rect name:(NSString*)name
  type:(NSString*)type toView:(UIView*)view {
  UIImageView *imgView = [[UIImageView alloc] initWithFrame:rect];
  imgView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]
    pathForResource:name ofType:type]];
  [self.view addSubView:imgView];     }
  [imgView release];
  return imgView;
}

// somewhere in app code
[MyClass addIconWithRect:CGMakeRect(0,0,32,32) name:@"ico-date"
  type:@"png" toView:parentView];

4) 在 UIImage 或 UIImageView 上创建一个 Objective-C 类别

5) 在要添加 UIImageView 的视图上创建一个方法

- (void)addIconWithRect:(CGRect)rect name:(NSString*)name type:(NSString*)type {
  UIImageView *imgView = [[UIImageView alloc] initWithFrame:rect];
  imgView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]
    pathForResource:name ofType:type]];
  [self.view addSubView:imgView];     }
  [imgView release];
  return imgView;
}

6)创建一个助手类

与选项 (3) 类似,但将静态方法放在单独的类中,该类仅用于重复代码部分的实用方法,例如调用帮助程序类“UIUtils”。

7) 使用 C 内联函数

static inline UIImageView* myfunc(CGFloat x, CGFloat y, CGFloat w, CGFloat h,
  NSString* name, NSString* type, UIView* parent) {
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:
      CGRectMake(x,y,w,h)]; 
    imgView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]
      pathForResource:name ofType:type]];
    [self.view addSubview:imgView]; 
    [imgView release];
    return imgView;
}

8)使用循环重复执行相同的代码

9) 使用普通的非静态 Objective-C 方法

就我个人而言,对于您的特定示例,我不会选择这些,而只是将其写出来,除非它在文件中重复十次以上,在这种情况下,我可能会选择(3)。如果它在很多文件中使用,我可能会选择(6)。

编辑:(3)和(6)的扩展描述,并注意我何时使用(6)。

编辑:添加了选项 8 和 9。修复了内存泄漏和一些错误。

编辑:更新代码以使用 imageWithContentsOfFile 而不是 imageNamed。

于 2010-01-18T17:43:13.767 回答
0

有几种方法

  • 子分类

把它放在一个基类中,然后从那个继承,不要大惊小怪

  • 共享方法

参数化使用self并改为将 UIView* 作为您想要添加的参数传递。然后将该方法粘贴在一个可从各处访问的单个类中,并仅在适当时调用它。

  • 类别

创建一个类似 UIImageView+Icon 的类别并将代码放在那里,然后您可以将其缩短为类似[self.view addSubview:[UIImageView icon:@"ico-date.png"]]

于 2010-01-18T17:24:39.617 回答