点击按钮访问在viewDidLoad中创建的NSMutableArray



在我的应用程序中,当用户点击按钮时,我会播放一个动画。在按钮点击的IBAction方法中,我让它创建一个NSMutable数组,将图像加载到数组中,然后循环浏览图像。

这会导致按钮点击和动画播放之间有相当大的延迟,但之后的每一次点击都很好,因为数组已经用图像创建。

我曾尝试将数组创建和图像加载放在vieDidLoad方法中,但由于某种原因,IBAction方法(循环图像的调用所在地)无法访问数组。如何使阵列对它可用?

- (IBAction)tap {
NSMutableArray *anim = [[NSMutableArray alloc]initWithObjects:[UIImage      imageNamed:@"0001.png"], ...(x30)... nil];
type.animationImages  = anim;
    type.animationDuration = 1.0;
    type.animationRepeatCount = 1;
    [type startAnimating];
}

UIViewController .h文件中定义NSMutableArray *anim。它将使全局用户可以访问.m文件中的任何位置。

- (void) viewDidLoad
{
    anim = [[NSMutableArray alloc]initWithObjects:[UIImage imageNamed:@"0001.png"], ...(x30)... nil];
}
- (IBAction)tap 
{
    type.animationImages  = anim;
    type.animationDuration = 1.0;
    type.animationRepeatCount = 1;
    [type startAnimating];
}

在.h文件中定义NSMutableArray*anim,即类成员变量

在视图中,DidLoad方法定义如下:

anim = [[NSMutableArray alloc]initWithObjects:[UIImage      imageNamed:@"0001.png"], ...(x30)... nil];

在按钮事件中这样使用:

 - (IBAction)tap 
{
  type.animationImages  = anim;
  type.animationDuration = 1.0;
  type.animationRepeatCount = 1;
  [type startAnimating];
}

试试这个简单的代码,它可能对你有帮助。数组在您第一次点击时分配一次。

if(!anim)
{
NSMutableArray *anim = [[NSMutableArray alloc]initWithObjects:[UIImage      imageNamed:@"0001.png"], ...(x30)... nil];
   NSLog(@"array allocate");
}else
    {
       NSLog(@"array already allocated");
     }

最新更新