Stella Stella - 4 years ago 135
Objective-C Question

iOS - Storing multiple values in one variable

I am creating 5 integer variables to store 5 different values in Objective C. For ex: intA, intB etc

Below is just sample code:

For example:

for (Desframe *obj in [myval allValues])
{
if (obj.A>10.0) {
myLabel.text = @"A";
intA = intA++;
}
else if (obj.B>10.0) {
myLabel1.text = @"B";
intB = intB++;
}
else if (obj.C>10.0) {
myLabe2.text = @"C";
intC = intC++;
}
else if (obj.D>10.0) {
myLabe3.text = @"D";
intD = intD++;
}
else if (obj.E>10.0) {
myLabe4.text = @"E";
intE = intE++;
}
}


In future, I may need to add 2 more variables.
I would like to know how to avoid creating 5 different integer variables but have 5 different values stored in one variable. Should I use array?
(or) how to handle this code professionally?

But I want this variable to be accessed globally in the same class (.m) file.

Kindly share your suggestion and guidance.

Answer Source

Yes, you can use an NSMutableArray for this. However, Objective-C NSArrays are a little strange since they can only contain objects. You'll have to "box" the entries as NSNumber objects:

NSMutableArray *numbers = @[@(1), @(2), @(3), @(4), @(5)];

And then you can fetch an item from the array:

NSNumber *aNumber = numbers[0];

But NSNumber Objects are immutable.

You might want to use a C-style array:

UInt64 numbers[] = [1, 2, 3, 4, 5];

Then you could say

numbers[0]++;

But with a statically allocated C-style array you can't add elements to the array at runtime.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download