Add to NSMutableArray - iphone

I have 2 doubles with each iteration I want add to a NSMutableArray but I can't seem to make it happen.
NSMutableArray *touchArray = [[NSMutableArray alloc]init];
[touchArray addObject:[NSString stringWithFormat:#"%d", "%d", tapTotal, touchBegin]];
NSLog(#"array: %#", touchArray);
The console prints 14108 as the value for the array, I'm not sure where that's coming from, it's not the value of either on of the variables. And XCode complains on the first two lines, "local declaration of 'touchArray' hides instance variable. I know I'm doing at least one thing wronl
Thanks for any help,
Robert

first, the 'local declaration problem':
You have already declared touchArray elsewhere, therefore you don't need to redeclare, just (possibly) initialize like so touchArray = [[NSMutableArray alloc] init];
Secondly: the double problem: theres quite a few:
you are adding a string to the array, not two doubles. to add a double, you need to wrap it in an NSNumber first:
[touchArray addObject:[NSNumber numberWithDouble:firstDouble]];
[touchArray addObject:[NSNumber numberWithDouble:secondDouble]];
also you want to print out each variable in the array to check it I would believe, not the array object itself. for this: NSLog(#"array[0] = %g", [[touchArray objectAtIndex:0] doubleValue]
edit for answer clarification: my answer assumes the poster wants to add two doubles seperately to the array, not a string with two values in it. Thought i might clear that up as kenny and I had different outtakes :)
there is a lot wrong here, so I would suggest maybe trying to read an objective c/iphone development book to learn more.

You are using +stringWithFormat: wrongly. Only the first string can be the format string. The rest will be passed as parameter to format. In your code, the format string is "%d", so the runtime will expect exactly 1 integer. It sees the address to the 2nd "%d" is 14108, so it will print this as an integer.
The correct code should be:
[NSString stringWithFormat:#"%g %g", tapTotal, touchBegin]
(Usually, %d → int, %u → unsigned, %g → double and CGFloat, %# → Objective-C objects, etc.)

"local declaration of 'touchArray' hides instance variable" shows you already have defined same array anywhere else in the code locally. Or you defined it into your .h file
NSLog cant directly print what you have inside a array. If you added a string as its first object (i.e. index 0) then you should print like this-
NSLog(#"array: %#", [touchArray objectAtIndex:0]);
Cheers

Related

get ascii code from string in xcode for iphone app

hey just a couple quick noob questions about writing my first ios app. Ive been searching through the questions here but they all seem to address questions more advanced than mine so im getting confused.
(1) All I want to do is turn a string into an array of integers representing the ASCII code. In other words, I want to convert:
"This is some string. It has spaces, punctuation, AND capitals."
into an array with 62 integers.
(2) How do I get back from the NSArray to a string?
(3) Also, are these expensive operations in terms of memory or computation time? It seems like it might be if we have to create a new variable at every iteration or something.
I know how to declare all the variables and im assuming I run a loop through the length of the string and at each iteration I somehow get the character and convert it into a number with some call to a built in command.
Thanks for any help you can offer or links to posts that might help!
if you want to store the ascii values in an nsarray it is going to be expensive. NSArray can only hold objects so you're going to have to create an NSNumber for each ASCII value:
unsigned len = [string length];
NSMutableArray arr = [NSMutableArray arrayWithCapacity:len];
for (unsigned i = 0; i < len; ++i) {
[arr addObject:[NSNumber numberWithUnsignedShort:[string characterAtIndex:i]]];
}
2) to go back to an NSString you'll need to use an MSMutableString and append each byte to the NSMutableString.
After saying that I'd suggest you don't use this method if you can avoid it.
A better approach would be to use #EmilioPelaez's answer. To go back from a memory buffer to an NSString is simple and inexpensive compared to iterating and concatting strings.
NSString * stringFromMemory = [[NSString alloc] initWithBytes:buffer length:len encoding: NSASCIIStringEncoding];
I ended up using the syntax I found here. Thanks for the help
How to convert ASCII value to a character in Objective-C?
NSString has a method to get the characters in an array:
NSString *string = "This is some string. It has spaces, punctuation, AND capitals.";
unichar *buffer = malloc(sizeof(unichar) * [string lenght]);
[string getCharacters:buffer range:NSMakeRange(0, [string length])];
If you check the definition of unichar, it's an unsigned short.

Methods in NSString

I am new to objective C and I am in a position where I need to create an iPhone App Really quickly , I am using XCode 4.2
I have a string (assuming the string is called string1) of type NSString and I would like to copy som charaters from this string into another NSString (called string2) I would like to do the following algorithm
If ( string1.char 1 ='a' and string1.char 2 ='b' and string1.char3='c')
{
string2.char1=string1.char4
string2.char2=string1.char5
string2.char3=string1.char6
}
I am not saying that the above code is executable , but this is the idea I would like to implement
also , do I need to add other framwork , synthestize any variable ? as I mentioned I am very new to all this
Thanks alot!
First off, looking at Apple's documentation is always a good idea. Just google 'NSString Class Reference.'
Second, NSString has a few methods that do what you desire, one being
[string1 characterAtIndex:myIndex];
where 'myIndex' is an NSUInteger (basically an int) of your index of interest.
With that method, you can specify an index of the string (remember, these start at 0, not 1), and check what character resides there.
if([string1 characterAtIndex:0] == 'a') {
//do something
}
Also, you can use
[string1 substringToIndex:myIndex];
to create a substring (smaller version of the original string, which would be string1) that is made up of the characters in string1 starting from index 0 (first character) and going to the index you specify.
The method
[string1 substringFromIndex:myIndex];
works similarly, but creates a substring starting at the given index and moving to the end of the string.
Also, it is important to note that strings created with the above to methods, for example:
NSString* stringTwo = [string1 substringToIndex:5];
are autoreleased, which means that the string referenced by the variable 'string1' can and will soon be wiped from memory unless you reserve the rights to use it by claiming ownership of it. The way you reserve rights to an object by claiming ownership of it (officially known as 'retaining' the object) is by calling
[string1 retain];
Now you own that object, and Objective C promises not to free that memory until you release ownership of it using
[string1 release];
if ([[string1 substringWithRange:(NSRange){0, 3}] isEqualToString #"abc"]){
string2 = [string1 substringWithRange:(NSRange){0, 3}];
}
where: (NSRange){startingIndex, length}
This is using the format you mentioned in your question.

How do you split NSString into component parts?

In Xcode, if I have an NSString containing a number, ie #"12345", how do I split it into an array representing component parts, ie "1", "2", "3", "4", "5"... There is a componentsSeparatedByString on the NSString object, but in this case there is no delimiter...
There is a ready member function of NSString for doing that:
NSString* foo = #"safgafsfhsdhdfs/gfdgdsgsdg/gdfsgsdgsd";
NSArray* stringComponents = [foo componentsSeparatedByString:#"/"];
It may seem like characterAtIndex: would do the trick, but that returns a unichar, which isn't an NSObject-derived data type and so can't be put into an array directly. You'd need to construct a new string with each unichar.
A simpler solution is to use substringWithRange: with 1-character ranges. Run your string through a simple for (int i=0;i<[myString length];i++) loop to add each 1-character range to an NSMutableArray.
A NSString already is an array of it’s components, if by components you mean single characters. Use [string length] to get the length of the string and [string characterAtIndex:] to get the characters.
If you really need an array of string objects with only one character you will have to create that array yourself. Loop over the characters in the string with a for loop, create a new string with a single character using [NSString stringWithFormat:] and add that to your array. But this usually is not necessary.
In your case, since you have no delimiter, you have to get separate chars by
- (void)getCharacters:(unichar *)buffer range:(NSRange)aRange
or this one
- (unichar)characterAtIndex:(NSUInteger) index inside a loop.
That the only way I see, at the moment.
Don't know if this works for what you want to do but:
const char *foo = [myString UTF8String]
char third_character = foo[2];
Make sure to read the docs on UTF8String

How to find and replace symbols in a string?

I know it must be a very simple thing to do but I've never had to treat strings before (in Objective-C) and apparently there's not RegEx on Cocoa-Touch.
Well, the situation is:
I have a text field to get a value (money, such as 32.10 for instance).
The problem:
If the user types in a symbol such as #, /, # etc. my app will crash.
The Question: How can I treat this string to remove the symbols if there are any?
you can try this:
NSString *s = #"12.827##584";
NSCharacterSet *removeCharSet = [NSCharacterSet characterSetWithCharactersInString:#"/:##"];
s = [[s componentsSeparatedByCharactersInSet: removeCharSet] componentsJoinedByString: #""];
NSLog(#"%#", s);
You do get regex in Cocoa Touch.
Here's a good discussion of the varying degrees of regex power in iOS, the blocks example at the end should get you most of the way there.
http://volonbolon.net/post/861427732/text-handling-in-ios-4
I understand you're trying to figure out the number included in the UITextFields's text property and assign it to a float variable.
Try using an NSScanner for this:
NSScanner* textScanner = [NSScanner localizedScannerWithString:textfield.text];
float* floatValue;
[textScanner scanFloat:&floatValue];
floatValue now contains the parsed float value of your textfield.

How a get a part of the string from main String in Objective C

I have mainString from which i need to get the part of the string after finding a keyword.
NSString *mainString = "Hi how are you GET=dsjghdsghghdsjkghdjkhsg";
now I need to get the string after the keyword "GET=".
Waiting for a reply.
Have a look at the NSString documentation.
Assuming your string really is so totally straightforward, you could do something like this:
NSArray *components = [mainString componentsSeparatedByString: #"GET="];
NSString *stringYouWant = [components objectAtIndex: 1];
Obviously, this performs absolutely no error checking and makes a number of assumptions about the actual contents of mainString, but it should get you started.
Note, also, that the code is somewhat defensive in that it assumes that you are looking for GET= and not separating on =. Either way is a hack in terms of parsing, but... hey... hacks are sometimes the right answer.
You can use a regex via RegexKitLite:
NSString *mainString = #"Hi how are you GET=dsjghdsghghdsjkghdjkhsg";
NSString *matchedString = [mainString stringByMatching:#"GET=(.*)" capture:1L];
// matchedString == #"dsjghdsghghdsjkghdjkhsg";
The regex used, GET=(.*), basically says "Look for GET=, and then grab everything after that". The () specifies a capture group, which are useful for extracting just part of a match. Capture groups begin at 1, with capture group 0 being "the entire match". The part inside the capture group, .*, says "Match any character (the .) zero or more times (the *)".
If the string, in this case mainString, is not matched by the regex, then matchedString will be NULL.
You can get the location of the first occurrence of = and then just take a substring of mainString from the location of = to the end of the string.