iphone - 显示 NSArray 中的每个对象 2 秒

标签 iphone ios objective-c xcode

我遇到以下问题:我有一个包含 5 个对象的 NSArray。我想使用 NSTimer 显示每个项目 2 秒,并在显示数组中的最后一个项目后释放计时器。

Country = [NSArray arrayWithObjects:@"Aus",@"India",@"Pak",@"China",@"Japan", nil];

cntcount = [Country count];
NSLog(@"concount=%i", cntcount);

[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(startTime) userInfo:nil repeats:YES];

但我没有再迈出一步。我应该在 starttime() 函数中做什么?请帮忙!

//
//  AppViewController.m
//  NSTimerExample
//

#import "AppViewController.h"

@interface AppViewController ()

@end

@implementation AppViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    Country = [NSArray arrayWithObjects:
                  @"Aus", @"India", @"Pak", @"China", @"Japan", nil];

    tempValue = 0; 
    NSTimer *popupTimer = [NSTimer scheduledTimerWithTimeInterval:2.0
                                                           target:self
                                                         selector:@selector(startTime:)
                                                         userInfo:nil
                                                          repeats:YES];
    NSRunLoop *runner = [NSRunLoop currentRunLoop];
    [runner addTimer:popupTimer forMode:NSDefaultRunLoopMode];

}

- (void)startTime:(NSTimer *)theTimer {
    int cntcount = [Country count];
    if(tempValue < cntcount) {

        NSString *objectName = [Country objectAtIndex:tempValue];
        NSLog(@"objectName=%@", objectName);

        tempValue++;
    } else {
        [theTimer invalidate];
        theTimer = nil;
        // or you can reset tempValue to 0.

    }
}

显示最后一个项目后,我想释放计时器,因为不再需要它,但我收到了 EXC_BAD_ACCESS 异常。

最佳答案

这样做,

.h

int tempValue;

.m

tempValue=0;     
NSTimer *popupTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(startTime:) userInfo:nil repeats:YES];;
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:popupTimer forMode: NSDefaultRunLoopMode];

在计时器操作方法中:

-(void)startTime:(NSTimer*)theTimer {
    if(tempValue< Country.count) {

         // Display array object eg: label.text=[Country objectAtIndex:tempValue];

         tempValue++;
    } else {
        [theTimer invalidate];
        theTimer=nil;
        // or you can reset the tempValue into 0.

    }
}

关于iphone - 显示 NSArray 中的每个对象 2 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16733768/

相关文章:

iphone - 使用 NSPredicate 过滤数组导致第二次尝试 exc_bad_access

iphone - iPhone 上的灰度图像的图像数据是如何解释的?

ios - 应用程序发送旧推送和新推送

ios - 动态删除元素时如何使用自动布局?

iphone - 正确[ super dealloc]

ios - 多点连接框架 : Stability and Recommendations

iphone - jquery mobile 按钮无法正确显示

iphone - UILabel 在第 3 代和第 4 代 iPod 上的显示方式有所不同

iphone - 以编程方式获取设备的电话号码

iphone - ios 自动布局 : Programmatically set width constraint