Objective-C string arrays - objective-c

I have a string array as such:
NSArray *names;
names = [NSArray arrayWithObjects:
#"FirstList",
#"SecondList",
#"ThirdList",
nil];
I'm trying to assign an element of this string array to a string variable as such:
NSString *fileName = names[0]; // "Incompatible types in initialization"
or with casting
NSString *fileName = (NSString)names[0]; // "Conversion to non-scalar type requested"
I'm trying to do this, so I can use the string in a method that takes a string as an argument, such as:
NSString *plistPath = [bundle pathForResource:filetName ofType:#"plist"];
Is there no way to assign an element of a string array to a string variable?
Update from 2014: The code in this post actually would work these days since special syntactic support has been added to the framework and compiler for indexing NSArrays like names[0]. But at the time this question was asked, it gave the error mentioned in this question.

You don't use C array notation to access NSArray objects. Use the -objectAtIndex: method for your first example:
NSString *fileName = [names objectAtIndex:0];
The reason for this is that NSArray is not "part of Objective-C". It's just a class provided by Cocoa much like any that you could write, and doesn't get special syntax privileges.

NSArray is a specialized array class unlike C arrays. To reference its contents you send it an objectAtIndex: message:
NSString *fileName = [names objectAtIndex:0];
If you want to perform an explicit cast, you need to cast to an NSString * pointer, not an NSString:
NSString *fileName = (NSString *)[names objectAtIndex:0];

With the new Objective-C literals is possible to use:
NSString *fileName = names[0];
So your code could look like this:
- (void)test5518658
{
NSArray *names = #[
#"FirstList",
#"SecondList",
#"ThirdList"];
NSString *fileName = names[0];
XCTAssertEqual(#"FirstList", fileName, #"Names doesn't match ");
}
Check Object Subscripting for more information.

Related

How do I add a character to an already existing string?

When I make:
NSString x = #"test"
How do I edit it so that it becomes "testing"?
And when I put:
NSMutableString x = [[NSMutableString alloc] initWithString:#"test"];
There is an error that says:
Initializer element is not a compile-time constant.
Thanks
When declaring NSMutableString, you missed the asterisk:
NSMutableString *x = [[NSMutableString alloc] initWithString:#"test"];
// Here --------^
With a mutable string in hand, you can do
[x appendString:#"ing"];
to make x equal testing.
You do not have to go through a mutable string - this will also work:
NSString *testing = [NSString stringWithFormat:#"%#ing", test];
You need to declare your NSString or NSMutableString as *x. These are pointers to objects.
To change a string in code is quite easy, for example:
NSString *test = #"Test";
test = [test stringByAppendingString:#"ing"];
And the value in test will now be Testing.
There are a lot of great NSString methods, both instance and class methods, for manipulating and working with strings. Check the documentation for the complete list!
if you want to add multiple or single strings to an existing NSString use the following
NSString *x = [NSString stringWithFormat:#"%#%#", #"test",#"ing"];

Construct NSString from the description method of each NSArray item?

I have an NSArray, where each object contains a specific class called Card. Card has a description method. I want to join all objects in the array using the output of the description method, separated by spaces. Is there a simple to do this, without manually iterating the NSArray and manipulating NSString?
Something akin to the following made-up code?
NSArray *myArray = getCards(); // fetches 10 items or more
NSString *myString = [myArray joinUsingDescriptionMethodSeparatedBy:#" "];
or
NSString *myString = [NSString stringFromArrayDescriptionMethods:myArray separatedBy:#" "];
Naturally ,I could implement this myself but I suspect there could be something already present that does this.
I don't think that there is such a method. You can also implement it in a Category for NSString.
Sorry, I found this:
NSString * result = [[array valueForKey:#"description"] componentsJoinedByString:#""];
From the documentation:
Constructs and returns an NSString object that is the result of
interposing a given separator between the elements of the array.
- (NSString *)componentsJoinedByString:(NSString *)separator
Do this for description method of each NSArray item:
NSMutableString * result = [[NSMutableString alloc] init];
for (NSObject * obj in array)
{
[result appendString:[NSString stringWithFormat:#" %#"[obj description]]];
}
NSLog(#"The concatenated string is %#", result);

Change value of mutable string

How to change value of mutable string ? Here is what I do
NSString *str = #"This is string";
NSMutableString *str = [NSMutableString stringWithFormat:#"%#", str];
str = #"New string" -> wrong incompatible pointer types assigning to NSMutableString from NSString
You only need to use NSMutableString if you want to change parts of the string in place (append, insert etc.), often for performance reasons.
If you want to assign new values to the string variable, you're fine with a good old NSString as your last line simple assigns a complete new string object to str:
You can use setString to replace the whole string:
NSString *str = #"This is string";
NSMutableString *mutableStr = [NSMutableString stringWithFormat:#"%#", str];
...
[mutableStr setString:#"a different non mutable string"];
As indicated in another answer, a non-mutable NSString may be enough for your purposes.
This is how you should initialize a NSMutableString:
NSMutableString *string = [[NSMutableString alloc]init];
You could use any other way specified in the docs. The way you are doing it, you are not creating any instance of the NSMutableString class. Then, if you want to add some string to it:
[string appendString:#"content"];

Going crazy with UITextField

I'm literally going crazy whit these six rows of code.
NB: nome and prezzo are 2 textFields
NSString *itemName = (NSString *) [rowVals objectForKey:#"name"];
NSString *itemPrice = (NSString *) [rowVals objectForKey:#"price"];
nome.text = itemName;
nome.userInteractionEnabled = YES;
prezzo.text = itemPrice;
prezzo.userInteractionEnabled = YES;
Don't know why when itemPrice is copied in one of those label, the program go in SIGABRT.
Instead if I try to read the content with an NSLog(#"%#",itemPrice); it return the exact value, so it means that is a valid NSString.
The only solution I found is passing through a NSNumber:
NSNumber *itemPrice = (NSNumber *) [rowVals objectForKey:#"price"];
prezzo.text = [[NSString alloc] initWithFormat:#"%#", itemPrice];
There is another way to use directly the NSString?
Probably the value in the #"price" field is NSNumber, and not an NSString. The NSLog method will still provide a correct result, since %# is used for any NSObject subclass, not just NSString.
How about this:
NSString *itemPrice = [[rowVal objectForKey:#"price"] stringValue];
prezzo.text = itemPrice;
The problem might be the object type returned by [rowVals objectForKey:#"price"]. When you place the (NSString *) cast before the method call, you're telling the compiler what type of object is returned, but not actually converting it into an NSString. The line you use below does convert from NSNumber (or whatever other object) to a string: [[NSString alloc] initWithFormat:#"%#", itemPrice]
You might be storing NSNumber's object in NSDictionary instead of NSString.
There could be 2 ways: one would be to convert NSNumber to NSString while adding it to dictionary or the other way would be to convert NSNumber to NSString while assigning it to "itemName".
you may do the conversion for second option like:
NSString *itemPrice = [[rowVals objectForKey:#"price"]stringValue];

String parsing in Objective-C

When I have pf:/Abc/def/, how can I get the /Abc/def/?
With Python, I can use
string = 'pf:/Abc/def/'
string.split(':')[1]
or even
string[3:]
What's the equivalent function in Objective-C?
NSString *string = [NSString stringWithFormat:#"pf:/Abc/def/"];
NSArray *components = [string componentsSeparatedByString: #":"];
NSString *string2 = (NSString*) [components objectAtIndex:1];
Reference: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/componentsSeparatedByString:
componentsSeparatedByString will return an NSArray. You grab the object at a certain index, and type cast it to NSString when storing it into another variable.