添加和跟踪无限数量的对象的最佳方法是什么?

发布于 2024-12-25 11:35:35 字数 545 浏览 4 评论 0原文

我有一个按钮,点击该按钮后,会在视图内添加标签。此后无论何时点击它,它都会添加另一个标签,该标签从上一个标签结束的位置开始。

我尝试了这个

if (self.currentLabel == nil)  
     startingPoint = 0;
else
    startingPoint = currentLabel.frame.size.width + 5;

// Most recently created label becomes currentLabel
self.currentLabel = [[FormulaLabel alloc] initWithFrame:CGRectMake(startingPoint, 10, 100, 50)]; 

为了跟踪所有标签,我尝试将它们添加到数组中,

 [arrayOfObjects addObject:self.currentLabel] 

但我注意到数组计数没有改变。

为什么上面的代码不起作用,有没有更好的方法来跟踪无限数量的标签?

I have a button that, when tapped, adds a label inside a view. Anytime it is tapped after that, it adds another label that starts where the last one ended.

I tried this

if (self.currentLabel == nil)  
     startingPoint = 0;
else
    startingPoint = currentLabel.frame.size.width + 5;

// Most recently created label becomes currentLabel
self.currentLabel = [[FormulaLabel alloc] initWithFrame:CGRectMake(startingPoint, 10, 100, 50)]; 

To keep track of all the labels, I tried adding them to an array

 [arrayOfObjects addObject:self.currentLabel] 

but I noticed that the array count wasn't changing.

Why doesn't the above code work, and is there a better way to keep track of an indefinite amount of labels?

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

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

发布评论

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

评论(1

梦罢 2025-01-01 11:35:35

NSArray 是不可变的。您需要使用 NSMutableArray

如果您已经在使用 NSMutableArray,您会收到任何警告吗?

作为补充说明,“arrayOfObjects”是一个糟糕的名字。像“标签”、“usedLabels”或“labelHistory”之类的东西会更具描述性。

NSArrays are immutable. You need to use an NSMutableArray.

If you are already using a NSMutableArray, are you getting any warnings?

As an additional note, "arrayOfObjects" is a poor name. Something like "labels," "usedLabels" or "labelHistory" would be far more descriptive.

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