How to include a C array in -description - iphone

I'm trying to include the elements of an array in the NSString that's returned by the -description method in my class. No clue how to do this in Objective-C...in Java there's string concatenation or StringBuilder, what's the equivalent in Obj-C?
TIA..

Just use NSArray's componentsJoinedByString: method with whatever you want between them as the argument.
NSString *elementsSquishedTogether = [myArray componentsJoinedByString:#""];
NSString *connectedByACommaAndSpace = [myArray componentsJoinedByString:#", "];
If you have a C array, you can turn it into an NSArray with NSArray *converted = [NSArray arrayWithObjects:yourCArray count:yourArrayCount].

The title of your thread talks about C arrays, so here's a modification of jsumners' answer that will deal wiith C arrays.
myArray is assumed to be an ivar declared thusly:
int* myArray;
storage for myArray is assumed to be malloc'd at some point and the size of it is in an ivar declared:
int myArraySize;
The code for description goes something like
- (NSString *)description
{
NSMutableString *returnString = [[[NSMutableString alloc] init] autorelease];
for (int i = 0 ; i < myArraySize ; i++)
{
if (i > 0)
{
[returnString appendString: #", "];
}
[returnString appendFormat: #"%d", myArray[i]];
}
return [NSString stringWithFormat: #"[%#]", returnString];
}
There are variations. The above version formats the string with bracket delimiters and commas between elements. Also, it returns an NSString instead of an NSMutableString which is not a big deal, but I feel that if you say you are returning an immutable object, you probably should.

The following could should "build" a string representation of your array. Notice that it is using the -description method of the objects in the array. If you want something different you will have to make the necessary change.
- (NSString *)description: (id) myArr {
NSMutableString *returnString = [[[NSMutableString alloc] init] autorelease];
for (int i = 0, j = [myaArr count]; i < j; i++) {
[returnString appendString: [[myArr objectAtIndex: i] description]];
}
return [NSString stringWithString: returnString];
}
Edit:
As JeremyP said, I answered this using Objective-C arrays. I guess I just forgot the question when I started writing my code. I'm going to leave my answer as an alternative way to do it, though. I've also fixed the return string type from a mutable string to an immutable string (as it should be).

Related

Unable to create NSMutableArray using for-loop

i want to have an array with values "25 kg", "26 kg"... "149 kg", "150 kg". To simplify task i wrote this:
-(NSMutableArray*)weightArray{
NSMutableArray *myArray;
for (int i=25; i++; i<150){
NSString *weightString;
weightString = [NSString stringWithFormat:#"%d kg", i];
[myArray addObject:weightString];
}
return myArray;
}
And then in viewDidload in my view i wrote: NSLog (#"%#", [self weightArray]);
But it looks like it's not working. I might be missing something obvious like syntax. Why is it not working?
UPDATE:
Finally i found a solution - first, i declare weightArray in #implementation section, then i wrote:
-(void)fillingArray{
if (!weightArray){
for (int i=25; i<150 ;i++){
NSString *weightString = [[NSMutableArray alloc] init];
weightString = [NSString stringWithFormat:#"%d kg", i];
[weightArray addObject:weightString];
NSLog(#"%#", weightString);
}
}
}
In viewDidLoad i wrote:
[self fillingArray];
NSLog(#"%#", weightArray);
I think, my problem was in that string NSLog(#"%#", [self weightArray]); In square brackets it suppose to be method name, but i was trying to point at array, and nothing happening.
There are 3 problems with what you are doing.
You need to create your array like this: NSMutableArray *myArray = [[NSMutableArray alloc] init]; so that it will actually exist.
Your NSLog needs to be NSLog (#"%#", [self weightArray]); since you are lgging an array and not a number.
(thanks rmaddy for pointing this out) The 2nd and 3rd part of your for statement are reversed. So, i++ is your condition and is always non-zero. This infinite loop is what causes your machine to lock up.
EDIT: Here's a better way that only creates the array once.
-(NSMutableArray*)weightArray{
static NSMutableArray *myArray;
if (!myArray){
myArray = [[NSMutableArray alloc] init];
for (int i=25; i<150 ;i++){
NSString *weightString;
weightString = [NSString stringWithFormat:#"%d kg", i];
[myArray addObject:weightString];
}
}
return myArray;
}
You don't allocate and initialize the array. So it has an indeterminate value, and your program invokes undefined beahvior. Create it actually:
NSMutableArray *myArray = [NSMutableArray new];

How to create a comma-separated string?

I want to create a comma-separated string like this.
NSString *list = #"iPhone,iPad,iPod";
I tried like this,
[strItemList appendString:[NSString stringWithFormat:#"%#,", [[arrItems objectAtIndex:i]objectForKey:#"ItemList"]]];
But the issue is I'm getting a string like this
#"iPhone,iPad,iPod," Note that there is an extra comma "," at the end of the string. How can I avoid that extra comma?
Can you please give me a hint. Highly appreciated
Thanks in advance
To join an array of strings into a single string by a separator (character which would be a string), you could use this method of NSArray class:
NSArray* array = #[#"iPhone", #"iPad", #"iPod"];
NSString* query = [array componentsJoinedByString:#","];
By using this method, you won't need to drop the last extra comma (or whatever) because it won't add it to the final string.
There's a couple of routes you can take.
If the number of items is always the same, and known before hand (which I guess isn't the case, but I mention it for completeness's sake), just make the whole string at once:
[NSString stringWithFormat:#"%#,%#,%#", [[arrItems objectAtIndex:0] objectForKey:#"ItemList"]], [[arrItems objectAtIndex:1] objectForKey:#"ItemList"]], [[arrItems objectAtIndex:2] objectForKey:#"ItemList"]]
Knowing that the unwanted comma will always be the last character in the string, you can make removing it the last step in construction:
} // End of loop
[strItemList removeCharactersInRange:(NSRange){[strItemList length] - 1, 1}];
Or you can change your thinking a little and do the loop like this:
NSString * comma = #"";
for( i = 0; i < [arrItems count]; i++ ){
[strItemList appendString:[NSString stringWithFormat:#"%#%#", comma, [[arrItems objectAtIndex:i]objectForKey:#"ItemList"]]];
comma = #",";
}
Notice that comma comes before the other item. Setting that string inside the loop means that nothing will be added on the first item, but a comma character will be for every other item.
After Completion of loop add below stmt
strItemList = [strItemList substringToIndex:[strItemList length]-1]
check the value of array count if array count is last then add without comma else add with comma. try this out i am not sure to much about.
if([arrItems objectAtIndex:i] == arrItems.count){
[strItemList appendString:[NSString stringWithFormat:#"%#", [[arrItems objectAtIndex:i]objectForKey:#"ItemList"]]];
}
else {
[strItemList appendString:[NSString stringWithFormat:#"%#,", [[arrItems objectAtIndex:i]objectForKey:#"ItemList"]]];
}
Assuming that arrItems is an NSArray with elements #"iPhone", #"iPad", and #"iPod", you can do this:
NSArray *list = [arrItems componentsJoinedByString:#","]
NSArray with elements #"iPhone", #"iPad", and #"iPod"
NSString *str=[[arrItems objectAtIndex:0]objectForKey:#"ItemList"]]
str = [str stringByAppendingFormat:#",%#",[[arrItems objectAtIndex:1]objectForKey:#"ItemList"]]];
str = [str stringByAppendingFormat:#",%#",[[arrItems objectAtIndex:2]objectForKey:#"ItemList"]]];
NsLog(#"%#",str);
// Assuming...
NSDictionary *dictionary1 = [NSDictionary dictionaryWithObject:[NSArray arrayWithObjects:#"iPhone", #"iPodTouch", nil] forKey:#"ItemList"];
NSDictionary *dictionary2 = [NSDictionary dictionaryWithObject:[NSArray arrayWithObjects:#"iPad", #"iPad2", #"Apple TV", nil] forKey:#"ItemList"];
NSDictionary *dictionary3 = [NSDictionary dictionaryWithObject:[NSArray arrayWithObjects:#"iMac", #"MacBook Pro", #"Mac Pro", nil] forKey:#"ItemList"];
NSArray *arrItems = [NSArray arrayWithObjects:dictionary1, dictionary2, dictionary3, nil];
// create string list
NSString *strItemList = [[arrItems valueForKeyPath:#"#unionOfArrays.ItemList"] componentsJoinedByString:#", "];
NSLog(#"All Items List: %#", strItemList);
Output:
All Items List: iPhone, iPodTouch, iPad, iPad2, Apple TV, iMac, MacBook Pro, Mac Pro
This method will return you the nsmutablestring with comma separated values from an array
-(NSMutableString *)strMutableFromArray:(NSMutableArray *)arr withSeperater:(NSString *)saperator
{
NSMutableString *strResult = [NSMutableString string];
for (int j=0; j<[arr count]; j++)
{
NSString *strBar = [arr objectAtIndex:j];
[strResult appendString:[NSString stringWithFormat:#"%#",strBar]];
if (j != [arr count]-1)
{
[strResult appendString:[NSString stringWithFormat:#"%#",seperator]];
}
}
return strResult;
}

store each letter of NSString as object of NSMutableArray

I have an NSString of integer values. I need to add each one of the integers as a separate object in an NSMutableArray.
I tried characterAtIndex: but I keep getting errors…
P.s. I've solved over 30 problems thank's to stackoverflow's search, but didn't find any information on this problem.
NSMutableArray *results = [NSMutableArray array];
for (int i = 0; i < [string length]; i++)
{
NSString *substr = [string substringWithRange:NSMakeRange(i,1)];
[results addObject:[NSNumber numberWithInt:[substr intValue]];
}
NSLog(#" %# separated into: %#", string, results);
Consider looking at componentsSeparatedByString: or componentsSeparatedByCharactersInSet: for your purpose. Both methods are available on NSString.
If your integers are more than one digit or are space-separated, consider alternately using an NSScanner - you can read instances of NSInteger off the string one by one, wrap them in NSNumbers, and stick them in your array.

Split one string into different strings

i have the text in a string as shown below
011597464952,01521545545,454545474,454545444|Hello this is were the message is.
Basically i would like each of the numbers in different strings to the message eg
NSString *Number1 = 011597464952
NSString *Number2 = 01521545545
etc
etc
NSString *Message = Hello this is were the message is.
i would like to have that split out from one string that contains it all
I would use -[NSString componentsSeparatedByString]:
NSString *str = #"011597464952,01521545545,454545474,454545444|Hello this is were the message is.";
NSArray *firstSplit = [str componentsSeparatedByString:#"|"];
NSAssert(firstSplit.count == 2, #"Oops! Parsed string had more than one |, no message or no numbers.");
NSString *msg = [firstSplit lastObject];
NSArray *numbers = [[firstSplit objectAtIndex:0] componentsSepratedByString:#","];
// print out the numbers (as strings)
for(NSString *currentNumberString in numbers) {
NSLog(#"Number: %#", currentNumberString);
}
Look at NSString componentsSeparatedByString or one of the similar APIs.
If this is a known fixed set of results, you can then take the resulting array and use it something like:
NSString *number1 = [array objectAtIndex:0];
NSString *number2 = [array objectAtIndex:1];
...
If it is variable, look at the NSArray APIs and the objectEnumerator option.
NSMutableArray *strings = [[#"011597464952,01521545545,454545474,454545444|Hello this is were the message is." componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#",|"]] mutableCopy];
NString *message = [[strings lastObject] copy];
[strings removeLastObject];
// strings now contains just the number strings
// do what you need to do strings and message
....
[strings release];
[message release];
does objective-c have strtok()?
The strtok function splits a string into substrings based on a set of delimiters.
Each subsequent call gives the next substring.
substr = strtok(original, ",|");
while (substr!=NULL)
{
output[i++]=substr;
substr=strtok(NULL, ",|")
}
Here's a handy function I use:
///Return an ARRAY containing the exploded chunk of strings
///#author: khayrattee
///#uri: http://7php.com
+(NSArray*)explodeString:(NSString*)stringToBeExploded WithDelimiter:(NSString*)delimiter
{
return [stringToBeExploded componentsSeparatedByString: delimiter];
}

Convert char to int to NSString

I am writing some code to allow users to answer multiple choice questions. So I have an NSArray of values [#"value1", #"value2", ..]
I want to display them as:
A) value1
B) value2
The code I have is
for(int i = i; i < [values count]; i = i+1) {
NSString *displayValue = [[NSString alloc] initWithString:<NEED HELP HERE>];
displayValue = [displayValue stringByAppendingString:#") "];
displayValue = [displayValue stringByAppendingString:[values objectAtIndex:i];
}
The question I have is if there is where I have put , how could I convert i to the right ASCII character (A, B, C, etc) and initialize the string with that value
NSString *displayValue = [NSString stringWithFormat:#"%c",'A'-1+i];
and to get the whole string at once, use:
NSString *displayValue = [NSString stringWithFormat:#"%c) %#",'A'-1+i,
[values objectAtIndex:i]];
(ps. if you alloc an object, you must also release or autorelease, or you will "leak" memory)
Look at NSString:initWithFormat method, along with the String Programming Guide.