0
NSMutableArray *nameArray = [[NSMutableArray alloc] init];
[nameArray addObject:@"abc"];
[nameArray addObject:@"cdf"];
[nameArray addObject:@"jkl"];

//Use a for each loop to iterate through the array
for (NSString *s in nameArray) {
    NSLog(@"value is %@", s);
}

The above code shows all the values of nameArray. But I want to assign all those values to these NSString:

NSString *a;
NSString *b;
NSString *cd;

An aray can have 1 or more elements but not more than 5.

Actually,I have 5 buttons, each button on click will add a NSString value(values are: f1,f2,f3,f4 and f5) to NSMutableArray. Now its upto the user if he clicks 2 buttons or 3 or 5 in a day. Now all these values will be saved in NSMutableArray (which can be 1 or 2 but not more than 5). That NSMutableArray will be saved in NSUserDefaults. This NSMutableArray than will be used in another view where I have some UIImageView (1,2,3,4 and 5). Now when I will get the string values from that Array(f1,f2,f3). If it is f1 then an image will be assigned to UIImage 1 if it is f3 then to image 3 and so on.

How to achieve this?

7
  • Why do you want this? because array may contain more than 3 elements, then? Commented Mar 14, 2012 at 12:56
  • Because these values need to be assigned to other variable for further use like for labels text. Yes you are right, but each array will not be having more than 5 elements. It can be 1 or more but not more than 5. How can I resolve this issue.? Commented Mar 14, 2012 at 12:58
  • So why not just do this myLabel.text = [nameArray objectAtIndex:0]; - by assigning them to other pointers you're running the risk of bad memory management :( Commented Mar 14, 2012 at 13:00
  • Yes, but I might be in need of saving these values to NSUserDefaults Commented Mar 14, 2012 at 13:03
  • I still have an impression that we are suggesting answers to a problem that can be solved in much more efficient way. If you could describe us a bit more in detail what you want to achieve, maybe we can help you better. Commented Mar 14, 2012 at 13:38

6 Answers 6

4

I would do something like that:

NSArray *array = [NSArray arrayWithObjects:@"A", @"B", @"C", @"D", @"E", nil];
NSString *a = nil, *b = nil, *c = nil, *d = nil, *e = nil;
NSUInteger idx = 0;

for ( NSString *string in array )
{
    switch ( idx++ ) {
        case 0: a = string; break;
        case 1: b = string; break;
        case 2: c = string; break;
        case 3: d = string; break;
        case 4: e = string; break;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hey Nicholas thank you, can you please tell me that this code will be working properly even if there are different number of elements like sometimes 4, sometimes 2.
Yes, it works for any number of objects in the array. If the array is smaller than 5, non assigned variables will be equal to nil. If the array is larger, additional values will be ignored.
2

As at least one element will be there in your array:

 NSString *a = (NSString *)[nameArray objectAtIndex:0];

As maximum will be five elements:

 for(int i = 1;i<[array count];i++)
 {
      if(i == 1)
      {
           NSString *b = (NSString *)[nameArray objectAtIndex:1];
      }
      else if(i == 2)
      {
           NSString *c = (NSString *)[nameArray objectAtIndex:2];
      }
      else if(i == 3)
      {
            NSString *d = (NSString *)[nameArray objectAtIndex:3];
      }
      else if(i == 4)
      {
           NSString *e = (NSString *)[nameArray objectAtIndex:4];
      }
 }

1 Comment

Yes tonio.mg, thanx, but the issue is that my array would have 1 element or more but not more than 5. Then how will it be resolved
1
a = [nameArray objectAtIndex:0];
b = [nameArray objectAtIndex:1];
cd = [nameArray objectAtIndex:2];

If you want to put your array elements into separate variables with distinct names, there is no automation in objective c (unlike say, in JavaScript) since it is a compiled and not a interpreted language. Something similar you can achieve with NSDictionary, i.e. to "index" objects with strings or whatever type you want.

5 Comments

Nevertheless if you explain us more precisely what do you want to do, maybe we can suggest you a more efficient / more "right" solution.
Actually,I have 5 buttons, each button on click will add a NSString value(values are: f1,f2,f3,f4 and f5) to NSMutableArray. Now its upto the user if he clicks 2 buttons or 3 or 5 in a day. Now all these values will be saved in NSMutableArray (which can be 1 or 2 but not more than 5). That NSMutableArray will be saved in NSUserDefaults. This NSMutableArray than will be used in another view where I have some UIImageView (1,2,3,4 and 5). Now when I will get the string values from that Array(f1,f2,f3). If it is f1 then an image will be assigned to UIImage 1 if it is f3 then to image 3 and so on
If you need only the information whether a user has clicked on the button or not, I would go for a fixed length array of a size of 5. When you load the buttons, you fill all elements of your array with 0. Then, when the user clicks say the 3rd button, you set the 3rd element of the array to 1. In the container of UIImageView you check for the 3rd image whether the 3rd element of the array is 0 or 1. Why would you need strings here?
Very nice approach, I didnt think of that, I was taking strings to achieve what you have defined. But How to implement this?
I added another answer with this approach.
1

You could go on with a simple C array of 5 unsigned chars, where the index of the array would point to your data. Something like this:

unsigned char nameArray[5] = {0, 0, 0, 0, 0};

// if you want to set the 3rd variable, use:
nameArray[2] = 1;

// to query:
if (nameArray[2]) { ... }

// When you need to save it to NSUserDefaults, wrap it into an NSData:
NSData* nameData = [NSData dataWithBytes:nameArray length:sizeof(nameArray)];
[[NSUserDefaults standardUserDefaults] setObject:nameData forKey:@"myKey"];

// To query it:
NSData* nameData = [[NSUserDefaults standardUserDefaults] dataForKey:@"myKey"];
const unsigned char* nameArray2 = [nameData bytes];
unsigned char second = nameArray2[2];

EDITED: corrected array access

7 Comments

Why do you wrap the NSArray with an NSData wrapper? Storing an NSArray in a pref is perfectly fine.
Pay attention that nameArray in my code is not an NSArray, just a simple fixed size C array of unsigned chars. The other solution would be to wrap the integers into NSNumbers and put them into a real NSArray, but in this case this seems to me more overhead, however it is discussable.
Ah, didn't catch that. Coffee time ^_^ NSArrays certainly offer convenience, but at a great cost of speed reduction.
Thanks @MrTJ for the help, but while querying or getting back the array from nsuserdefaults I am getting this error: Array initializer must be an initializer list or string literal. How can I resolve this error, couldnt get any information on net
Hi, I corrected the code above. Basically the compiler could not decide compile time the size of the C array, so it should be initialized as a pointer. You can still use the [] operators to access elements of the array behind the pointer but pay extra attention not to use out of bound indexes (in your case > 4).
|
0

If there is at most five options the easiest way to do it is with an if-else-if chain.

NSString *label1 = nil, *label2 = nil, *label3 = nil, *label4 = nil, *label5 = nil; 
for (NSString *s in nameArray) {
    if (label1 == nil)
        label1 = s;
    else if (label2 == nil)
        label2 = s;
    else if (label3 == nil)
        label3 = s;
    else if (label4 == nil)
        label4 = s;
    else if (label5 == nil)
        label5 = s;
}

Comments

0
              NSString *str1=nil;
              NSString *str2=nil;
              NSString *str3=nil;
              NSString *str4=nil;
        for (LocationObject *objLoc in arrLocListFirstView)
            {
                if (objLoc.isLocSelected)
                {
                    for (LocationObject *obj in arrLocListFirstView)
                    {
                        if (str1 == nil)
                            str1 = objLoc.strLoc;
                        else if (str2 == nil)
                            str2 = obj.strLoc;
                        else if (str3 == nil)
                            str3 = obj.strLoc;
                        else if (str4 == nil)
                            str4 = obj.strLoc;
                    }

    NSString *combined = [NSString stringWithFormat:@"%@,%@,%@,%@", str1,str2,str3,str4];
                    lblLocation.text=combined; (displaying text in UILabel)
                }

            }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.