You probably want to have those object in an NSArray or another type of collection. Then you will be able to loop through the content and do the same operation on each element.
Using one method in place of many
-
11-03-2022 - |
سؤال
I am trying to learn Objective-C for iOS. I have tried researching this, but I must not be using the right keywords.
I have several labels that are simply named, Label1, Label2, etc. I also have a ton of code that basically looks the same except the Label# changes. Can I build one method and pass the number to it and shrink my app significantly?
المحلول
نصائح أخرى
Consider defining a new class, CisonLabel, which abstracts out the shared behavior of these labels. The CisonLabel holds the control, and also its associated data. So you'd say
CisonLabel *label1=[CisonLabel for: self.labelControl1 withIdentifier: 1];
CisonLabel *label2=[CisonLabel for: self.labelControl2 withIdentifier: 2];
The CisonLabel would have methods like:
- (void) update; // sets the label text, based on the identifier
As DRiis suggests, you can collect all your CisonLabels in a collectionm perhaps an NSArray.
- (void) updateLabels: (NSArray*) theLabels
{
for(CisonLabel *label in theLabels) [label update];
}
Your instinct is sound: abstract out shared behavior into a class, and avoid repeating yourself.