单击按钮时增加 NSArray

发布于 2025-01-07 10:31:42 字数 711 浏览 3 评论 0原文

我正在逐行读取文本文件,并将其存储到 NSArray 中。 我想要实现的是当用户单击按钮时增加 NSArray 的索引。

代码:

 text.editable = NO;
 NSString *fileString = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"firstyea" ofType:@"txt"] encoding:NSUTF8StringEncoding error:nil]; // reads file into memory as an NSString
 NSArray *lines = [fileString componentsSeparatedByString:@"\n"]; // each line, adjust character for line endings
 NSString *wat = [lines objectAtIndex:1]; 
 text.text = wat;
 [self.view addSubview:text];

因此,每当用户单击按钮时,我都必须将 objectAtIndex 加 1。 我可以在 C++ 中通过使用 int 类型的变量并说出类似 objectAtIndex:counter++ 的内容来完成此操作,但我不知道如何在 IOS 中执行相同的操作。

I'm reading a text file line by line, and storing it into a NSArray.
What I want to achieve is to increment the index of my NSArray when the user clicks a button.

Code:

 text.editable = NO;
 NSString *fileString = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"firstyea" ofType:@"txt"] encoding:NSUTF8StringEncoding error:nil]; // reads file into memory as an NSString
 NSArray *lines = [fileString componentsSeparatedByString:@"\n"]; // each line, adjust character for line endings
 NSString *wat = [lines objectAtIndex:1]; 
 text.text = wat;
 [self.view addSubview:text];

So I have to increment objectAtIndex by 1 whenever the user clicks a button.
I can do it in C++ by having a variable of type int, and saying something like objectAtIndex:counter++ but I don't know how to do the same thing in IOS.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

最舍不得你 2025-01-14 10:31:43

你不能用 NSArray 做到这一点,你需要使用 NSMutableArray
您应该采用static int 类型的变量。

例如:

static int counter=0; //define it globally

NSMutableArray *tempArray=[[NSMutableArray alloc] init];

[tempArray insertObject:@"Your Data From File" atIndex:counter++];

注意:使用完数组后不要忘记释放它!

You can't do it with NSArray, you need to use a NSMutableArray
You should take a variable of type static int.

For example:

static int counter=0; //define it globally

NSMutableArray *tempArray=[[NSMutableArray alloc] init];

[tempArray insertObject:@"Your Data From File" atIndex:counter++];

Note: Don't forget to release the array after you're finished using it!

望喜 2025-01-14 10:31:43

全局声明一个整数 i。 @property int i;

viewDidLoad

,声明i=0

-(IBAction)BtnClick:(id)sender

{

if ( i < lines.count )

{

   NSString *wat = [lines objectAtIndex:i];

   i=i+1;

}
}

希望这有帮助。

Declare an integer i globally. @property int i;

in

viewDidLoad

, declare i=0;

-(IBAction)BtnClick:(id)sender

{

if ( i < lines.count )

{

   NSString *wat = [lines objectAtIndex:i];

   i=i+1;

}
}

Hope this helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文