Grabbing a specific element of an array in Objective-C - objective-c

I'm splitting a string by ';', but want to specifically grab the first and second element.
I know with PHP it's just simply $array[0], just can't find anything for this for Objective-C
NSArray *tempArray = [returnString componentsSeparatedByString:#";"];
So here I have assigned my array, how can I go about getting the first and second element?

Its just simply [array objectAtIndex:0] in Objective-C ;-)

Starting with XCode 4.5 (and Clang 3.3), you may use Objective-C Literals:
NSString *tmpString1 = tempArray[1];

NSString *tmpString = [tempArray objectAtIndex:0];
NSLog(#"String at index 0 = %#", tmpString);
NSString *tmpString1 = [tempArray objectAtIndex:1];
NSLog(#"String at index 1 = %#", tmpString1);
You may also wish to do an IF statement to check tmpArray actually contains objects in before attempting to grab its value...
e.g.
if ([tempArray count] >= 2) {
// do the above...
}

Related

Check if it is possible to break a string into chunks?

I have this code who chunks a string existing inside a NSString into a NSMutableArray:
NSString *string = #"one/two/tree";
NSMutableArray *parts = [[string componentsSeparatedByString:#"/"] mutableCopy];
NSLog(#"%#-%#-%#",parts[0],parts[1],parts[2]);
This command works perfectly but if the NSString is not obeying this pattern (not have the symbol '/' within the string), the app will crash.
How can I check if it is possible to break the NSString, preventing the app does not crash?
Just check parts.count if you don't have / in your string (or only one), you won't get three elements.
NSString *string = #"one/two/tree";
NSMutableArray *parts = [[string componentsSeparatedByString:#"/"] mutableCopy];
if(parts.count >= 3) {
NSLog(#"%#-%#-%#",parts[0],parts[1],parts[2]);
}
else {
NSLog(#"Not found");
}
From the docs:
If list has no separators—for example, "Karin"—the array contains the string itself, in this case { #"Karin" }.
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/componentsSeparatedByString:
You might be better off using the "opposite" function to put it back together...
NSString *string = #"one/two/three";
NSArray *parts = [string componentsSeparatedByString:#"/"];
NSString *newString = [parts componentsJoinedByString:#"-"];
// newString = #"one-two-three"
This will take the original string. Split it apart and then put it back together no matter how many parts there are.

Modify Object while Iterating over a NSMutableArray

I was trying to modify an object from an array while iterating over it and couldn't find a nice way of doing it... This is what I've done, is there a simpler way of doing this? I've been googling for while but I couldn't find anything...
NSMutableArray *tempArray = [[NSMutableArray alloc]init];
NSArray *days = [restaurant.hours componentsSeparatedByString:#","];
for (NSString *day in days) {
NSString *dayWithOutSpace = [day stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[tempArray addObject:dayWithOutSpace];
}
days = [NSArray arrayWithArray:tempArray];
Thanks!
As suggested by others there might be better ways to accomplish the exact task in the question, but as a general pattern there is nothing wrong with your approach - build a new array.
However if you need to modify a mutable array, say because multiple objects reference it, there is nothing wrong with that either - that is why it is mutable after all! You just need to use standard iteration rather than enumeration - the latter is just the wrong tool for the job. E.g.:
NSMutableArray *anArray = ...
NSUInteger itemCount = [anArray count];
for(NSUInteger ix = 0; ix < itemCount; ix++)
{
// read from anArray[ix] and store into anArray[ix] as required
}
The way you do it is OK, since you are not modifying the array you are looping through.
Here is another way, a little less intuitive and probably not faster:
NSArray* days = [[[restaurant.hours componentsSeparatedByString:#" "] componentsJoinedByString:#""] componentsSeparatedByString:#","];
Considering your hours string is like: 2, 5, 6, 7 etc. you can use the string as #", " directly.
NSArray *days = [restaurant.hours componentsSeparatedByString:#", "];
Maybe it is better to eliminate all white spaces before separation.
NSString *daysWithOutSpaces = [restaurant.hours stringByReplacingOccurrencesOfString:#"[\\s\\n]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, restaurant.hours.length)];
NSArray *days = [daysWithOutSpaces componentsSeparatedByString:#","];

Neater way to write all these parameters

I have a bunch of saved nsuserdefault parameters that need to be written (20 cars to be exact). I am wondering what will be the neatest way to write this. I number it in order because I believe the for loop will be appropriate(not too sure). The code below represents a snippet of what I am trying to do.
NSString *emailBody=[NSString
stringWithFormat:#"%#, %#, %#",[[NSUserDefaults
standardUserDefaults]stringForKey:#"Car1"],[[NSUserDefaults
standardUserDefaults]stringForKey:#"Car2"],[[NSUserDefaults
standardUserDefaults]stringForKey:#"Car3"]];
There's no reason to save 20 separate items. Just put them in an array and store the array with setObject:forKey:. You can then fetch them all back as an array using stringArrayForKey: (or arrayForKey: or even just objectForKey:).
Once you have an array, creating a comma-separated list is very easy:
NSString *emailBody = [array componentsJoinedByString:#", "];
If you must store them as 20 items for compatibility, I would still pull them out of NSUserDefaults and put them in an array before actually using them.
Just use a for loop, something like this.
NSMutableArray *a = [NSMutableArray array];
for (int i=1;i<21;i++)
{
[a addObject:[NSString stringWithFormat:#"Car%d", i]];
}
Then just put the array into a string.
Slightly neater:
NSMutableString *emailBody = [[NSMutableString alloc] init];
for (unsigned i = 1; i <= 20; i++) {
if (i > 1)
[emailBody appendString:#", "];
[emailBody appendString:[[NSUserDefaults standardUserDefaults]
stringForKey:[StringWithFormat:#"Car%d", i]]];
}

splitting nsstring and putting into tableview

I am trying to split the string into parts and insert into a table how should i do it?
I got an error for splitting of the array which is: -[__NSArrayI componentsSeparatedByString:]: unrecognized selector sent to instance 0x7a421e0
NSArray *BusRoute = alightDesc;
int i;
int count = [BusRoute count];
for (i = 0; i < count; i++)
{
NSDictionary *dic = [BusRoute objectAtIndex: i];
NSDictionary *STEPS = [dic valueForKey:#"STEPS"];
NSString *AlightDesc = [STEPS valueForKey:#"AlightDesc"];
NSLog(#"AlightDesc = %#", AlightDesc);
NSArray *aDescArray = [AlightDesc componentsSeparatedByString:#","];
NSLog(#"aDescArray = %#", aDescArray);
}
This is the string which I'm splitting, i got it from the NSLog
AlightDesc = (
"Block1",
"Block2",
"Block3"
)
please help I'm stuck thanks.
Objective C is not a strongly typed language. All you know for sure about [STEPS valueForKey:#"AlightDesc"] is that it will return an object (of type id). When you wrote NSString *AlightDesc = [STEPS valueForKey:#"AlightDesc"] the compiler did not complain because NSString * is a valid object type. Unfortunately there is a logic error in your code so that what was actually stored under the key #"AlightDesc" is an NSArray. As others have mentioned, NSArray does not respond to componentsSeparatedByString: so you get an error at runtime.
The easy fix for this is to correct your logic: Either store an NSString in the first place or treat what you get out as an NSArray. As #janusfidel mentioned you can use an NSArray perfectly well in a table by using objectAtIndex: to get the string for the entry you want.
In some more complicated cases you may not know what you will be getting out of a dictionary for a particular key. In that case in Objective C you can just ask the object:
id anObject = [STEPS valueForKey:#"AlightDesc"];
if ([anObject isKindOfClass:[NSString class]]) {
NSString *aString = (NSString *)anObject;
// Treat as a string ...
} else if ([anObject isKindOfClass:[NSString class]]) {
// Object is an array ...
Your NSString *AlightDesc should look like this
NSString *AlightDesc = "Block1,Block2,Block3";
NSArray *aDescArray = [AlightDesc componentsSeparatedByString:#","];
If your string is what you say it is
AlightDesc = ("Block1","Block2","Block3");
then your string is the problem because it's already broken up.

How to print a single array element in Objective-C?

How to print a array element at particular index in Objective-C? My code looks like this:
NSString *String=[NSString StringWithContentsOFFile:#"/User/Home/myFile.doc"];
NSString *separator = #"\n";
NSArray *array = [String componetntsSeparatedByString:separator];
NSLog(#"%#",array);
I'm able to print the full contents of an array at once, but I want to assign the element at each index into a string, like...
str1=array[0];
str2=array[1];
str3=array[0];...this continues
How do I do this?
You want the objectAtIndex: method. Example:
NSString *str1 = [array objectAtIndex:0];
NSString *str2 = [array objectAtIndex:1];
NSString *str3 = [array objectAtIndex:2];
From the documentation:
objectAtIndex:
Returns the object located at index.
- (id)objectAtIndex:(NSUInteger)index
Parameters
index
An index within the bounds of the receiver.
Return Value
The object located at index.
Discussion
If index is beyond the end of the array (that is, if index is greater than or equal to the value returned by count), an NSRangeException is raised.
if this is only for debugging, you could try using po <> in the gdb.
As of clang version 3.3, you can use the [index] notation, so
NSString *str1 = array[0];
would work now. See here for details.