gpt4 book ai didi

objective-c - 以特定间隔显示 NSArray

转载 作者:行者123 更新时间:2023-12-03 17:31:29 24 4
gpt4 key购买 nike

我有一个 NSArray,我想以特定的时间间隔显示每个对象,例如:

NSArray *array = [NSArray arrayWithObjects:@"foo",@"bar",@"baz",nil];

并输出:

for (object in array) {
NSLog(@"%@", object);
// wait 3 seconds then show next object
}

所以它应该这样做:

foo 
... wait three seconds
bar
... wait three seconds
baz
... wait three seconds
repeat

我该怎么做?

最佳答案

最简单的方法是使用 block ...

您可以使用第三方类别探索如何使用 block 来执行此操作,例如: https://github.com/zwaldowski/BlocksKit

至于没有 block 的解决方案:

@property (nonatomic, strong) NSArray *myArray;
@property (nonatomic) NSInteger iteration;

- (void)awakeFromNib //Or equivalent method called when you want to start scheduling..
{
self.myArray = [NSArray arrayWithObjects:@"foo",@"bar",@"baz",nil];
self.iteration = 0;

[NSTimer scheduledTimerWithTimeInterval:3
target:self
selector:@selector(fireEvent)
userInfo:nil
repeats:YES]; //Will Fire every 3 seconds...
}

-(void)fireEvent
{
NSLog(@"%@", [self.myArray objectAtIndex:self.iteration]);
self.iteration++;
if (self.iteration>=self.myArray.count) self.iteration=0;
}

如果您要在显示数组中的所有元素后使计时器无效。执行以下操作:

-(void)awakeFromNib //Or equivalent method called when you want to start scheduling..
{
self.myArray = [NSArray arrayWithObjects:@"foo",@"bar",@"baz",nil];
self.iteration = 0;

[NSTimer scheduledTimerWithTimeInterval:3
target:self
selector:@selector(fireEvent:)
userInfo:nil
repeats:YES]; //Will Fire every 3 seconds...
}

-(void)fireEvent:(NSTimer*)timer
{
NSLog(@">>>> %@", [self.myArray objectAtIndex:self.iteration]);
self.iteration++;
if (self.iteration>=self.myArray.count) {
self.iteration=0;
[timer invalidate];
}
}

注意:后面的代码仅向 @selector(fireEvent:) 添加一个“:”。并读取fireEvent中的NSTimer引用作为参数。

关于objective-c - 以特定间隔显示 NSArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23898196/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com