I'm trying this code...
NSString *tileString = [[NSString alloc] init];
for (int i = 0; i < [[GameP objectForKey:#"groundMap"] length]; i += 5) {
tileString = [[GameP objectForKey:#"groundMap"] substringWithRange:NSMakeRange(i, 5)];
[tileString stringByAppendingString:#"0000"];
[sharedInstance.groundMap addObject:tileString];
}
The 5 char string that's coming from the object is "t0001", so I want to end up with "t0001000" but it's not working, when I check sharedInstance.groundMap all the strings in the array are still "t0001"
Should I be using NSMutableString instead?
You aren't assigning the result. Change this:
[tileString stringByAppendingString:#"0000"];
to:
titleString = [tileString stringByAppendingString:#"0000"];
There's a little more cleanup you can do too:
for (int i = 0; i < [[GameP objectForKey:#"groundMap"] length]; i += 5) {
NSString *tileString = [[GameP objectForKey:#"groundMap"] substringWithRange:NSMakeRange(i, 5)];
titleString = [tileString stringByAppendingString:#"0000"];
[sharedInstance.groundMap addObject:tileString];
}
Related
i have a uitableview, which gets populated by a pulling data from a website, so there is a new string for every cell. To that, i want to have show a HEX for the user, based on the text in the cell.
I have tryed myself to make it, without luck, but luckly found a javascript script which does what i try to do. This script, i now need to convert to obj-c, i have tryed it myself, but failed. I hope to get some help.
javascript: http://jsfiddle.net/sUK45/
My try in obj-c (here the strings aint based on the data from the web, but just an array):
unichar hash = 0;
NSArray *strings = [NSArray arrayWithObjects:#"MA", #"Ty", #"Ad", #"ER", nil];
for (int i = 0; i < [[strings objectAtIndex:indexPath.row] length]; i++) {
hash = [[strings objectAtIndex:indexPath.row] characterAtIndex:i] + ((hash < 5) - hash);
}
NSString *colour = #"#";
for (int i = 0; i < 3; i++) {
int value = (hash >> (i * 8)) & 0xFF;
colour = [NSString stringWithFormat:#"%#%d", colour, value];
}
NSLog(#"%#", colour);
But the data i get, aint a useable HEX - NSlog:
#2432550
#3600
#3400
#1200
Probably this is not the only one mistake. Change
hash = [[strings objectAtIndex:indexPath.row] characterAtIndex:i] + ((hash < 5) - hash);
to
hash = [[strings objectAtIndex:indexPath.row] characterAtIndex:i] + ((hash << 5) - hash);
UPDATE:
Also change
colour = [NSString stringWithFormat:#"%#%d", colour, value];
to
colour = [NSString stringWithFormat:#"%#%02x", colour, (unsigned int)value];
UPDATE2:
I have fixed one more error and simplified code:
unsigned int hash = 0;
NSArray *strings = [NSArray arrayWithObjects:#"MA", #"Ty", #"Ad", #"ER", nil];
NSString *string = [strings objectAtIndex:indexPath.row];
for (int i = 0; i < string.length; i++) {
hash = [string characterAtIndex:i] + ((hash << 5) - hash);
}
NSString *color = [NSString stringWithFormat:#"#%06x", hash % 0x1000000];
NSLog(#"%#", color);
So I am inserting a class object into an NSMutable array, and then I am trying to manage the specific properties of each indexed object.
Here I create the NsMutableArray:
self.currentPuzzle = [[NSMutableArray alloc]init];
for(int i = 0; i < [temp length]; i++){ //temp is a string containing #'s and dots.
AnswerSpecifier *objectToGetIntoArray = [[AnswerSpecifier alloc]init];
objectToGetIntoArray.value = [[temp substringWithRange:NSMakeRange(i, 1)] intValue];
[self.currentPuzzle addObject:objectToGetIntoArray];
}
and here I am trying to change the value property of each object. value is an int property.
for (int i = 0; i < [self.board.boardString length]; i++) {
[self.currentPuzzle objectAtIndex:i].value = [[self.board.boardString substringWithRange:NSMakeRange(i, 1)] intValue];
}
However I get an error saying that the property value was not found on object of type id. Should I just create a new array and assign it to the old one? Is there a better way to do this?
Split your code up. This makes it easier to read and debug.
for (int i = 0; i < [self.board.boardString length]; i++) {
AnswerSpecifier *answer = self.currentPuzzle[i];
NSString *boardString = [self.board.boardString substringWithRange:NSMakeRange(i, 1)];
int value = [boardString intValue];
answer.value = value;
}
You don't get points for cramming as much code as possible into one line.
But if you really just want to fix the one line you need to put the cast in the proper place:
[(AnswerSpecifier *)self.currentPuzzle[i] setValue:[[self.board.boardString substringWithRange:NSMakeRange(i, 1)] intValue]];
Try type casting the object
((AnswerSpecifier *)[self.currentPuzzle objectAtIndex:i]).value = [[self.board.boardString substringWithRange:NSMakeRange(i, 1)] intValue];
Try to replace with:
for (int i = 0; i < [self.board.boardString length]; i++) {
[[self.currentPuzzle objectAtIndex:i] setValue:[[self.board.boardString substringWithRange:NSMakeRange(i, 1)] intValue]];
}
Not sure exactly how to word this but basically I am doing this:
unsigned int propCount = 0;
objc_property_t *properties = class_copyPropertyList([self class], &propCount);
for(int idx = 0; idx < propCount; idx++) {
objc_property_t prop = *(properties + idx);
NSString *key = #(property_getName(prop));
NSString *key2 = #(property_getAttributes(prop));
NSLog(#"%#::%#", key,key2);
}
and it prints out
describeOther::T#"UITextField",&,N,V_describeOther
how can I assign "UITextField" to something or is it already assigned and I can access it like key2[1] or something??
EDIT:
I guess I could do a if statement with a contains constraint but not sure if thats the "cleanest" way to do it.
Get the range of the two double-quotes and extract the substring between those two ranges.
NSRange openQuote = [key2 rangeOfString:#"\""];
NSRange closeQuote = [key2 rangeOfString#"\"" options:NSBackwardsSearch];
NSUInteger start = openQuote.location + openQuote.length;
NSUInteger end = closeQuote.location;
NSRange nameRange = NSRangeMake(start, end - start);
NSString *name = [keys substringWithRange:nameRange);
I am having trouble with some code. I narrowed it down to this problem: first of all, reverseString and 2 are both NSMutableStrings _input1 and _input2 are NSStrings, i'm trying to add zeros to the smallest string but it's not working correctly, this is what I got. reverseString is #"123" and reverseString2 is #"34567".
//they get initialized back into the original strings
_input1=reversedString;
_input2=reversedString2;
//appends 0 to the shortest value
while ([_input1 length]>[_input2 length]){
_input2=[_input2 stringByAppendingString:#"0"];
_length=[_input1 length];
}
while ([_input1 length]<[_input2 length]){
_input1=[_input1 stringByAppendingString:#"0"];
_length=[_input2 length];
}
//converts the string to an NSArray
for (int i=0; i <([_input1 length]); i++) {
NSString *TempStr = [_input1 substringWithRange:NSMakeRange(i, 1)];
[one addObject:[TempStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}
for (int i=0; i <([_input2 length]); i++) {
NSString *TempStr2 = [_input2 substringWithRange:NSMakeRange(i, 1)];
[two addObject:[TempStr2 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}
Now I noticed that when it goes through this loop, the smallest one, _input1, gets set to #"" instead of adding zeros to the end. This is within a class, by the way.
This is also an error I receive:
objc[2291]: Method cache corrupted. This may be a message to an invalid object, or a memory error somewhere else.
objc[2291]: receiver 0x100300830, SEL 0x7fff8a689779, isa 0x7fff727b8bd0, cache 0x7fff727b8be0, buckets 0x7fff89b9b09c, mask 0x1, occupied 0x0, wrap bucket 0x7fff89b9b09c
objc[2291]: receiver 0 bytes, buckets 0 bytes
objc[2291]: selector 'length'
(lldb)
Just try with following code
if([_input1 length] > [_input2 length])
{
for (int i = 0 ; i < [_input1 length] - [_input2 length] ; i ++)
_input2 = [_input2 stringByAppendingString:#"0"];
}
else
{
for (int i = 0 ; i < [_input2 length] - [_input1 length] ; i ++)
_input1 = [_input1 stringByAppendingString:#"0"];
}
Try like this:-
NSString *input1=#"123";
NSString * input2=#"34567";
NSMutableArray *one=[NSMutableArray array];
NSMutableArray *two=[NSMutableArray array];
//appends 0 to the shortest value
while ([input1 length]>[input2 length]){
input2=[input2 stringByAppendingString:#"0"];
//length=[input1 length];
}
while ([input1 length]<[input2 length]){
input1=[input1 stringByAppendingString:#"0"];
// length=[input2 length];
}
for (int i=0; i <([input1 length]); i++) {
NSString *TempStr = [input1 substringWithRange:NSMakeRange(i, 1)];
[one addObject:[TempStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}
NSLog(#"%ld",[one count]);
for (int i=0; i <([input2 length]); i++) {
NSString *TempStr2 = [input2 substringWithRange:NSMakeRange(i, 1)];
[two addObject:[TempStr2 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}
NSLog(#"%ld",[two count]);
Well your requirements are not very clear, but here's a cleaner version of the code you proposed
NSString *string1 = #"foo";
NSString *string2 = #"foobar";
// Compute the desired length
NSUInteger length = MAX(string1.length, string2.length);
// We will pad using this string
NSString *paddingString = #"0";
// Pad both strings to the same length
string1 = [string1 stringByPaddingToLength:length withString:paddingString startingAtIndex:0];
string2 = [string2 stringByPaddingToLength:length withString:paddingString startingAtIndex:0];
// Build two arrays containing the characters, percent escaped
NSMutableArray *charactersArray1 = [NSMutableArray arrayWithCapacity:string1.length];
NSMutableArray *charactersArray2 = [NSMutableArray arrayWithCapacity:string2.length];
for (NSInteger i = 0; i < string1.length; i++) {
[charactersArray1 addObject:[[string1 substringWithRange:(NSRange){ i, 1 }] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[charactersArray2 addObject:[[string2 substringWithRange:(NSRange){ i, 1 }] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}
NSLog(#"String 1: %#\nString 2: %#", charactersArray1, charactersArray2);
The result will be
String 1: [ f, o, o, 0, 0, 0 ]
String 2: [ f, o, o, b, a, r ]
I figured out my problem, _input1 and _input2 were bad pointers and i had to fix it, sorry for all the confusion, in the end i got my code to work!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am writing code which should reverse a string. When I run the following code it throws an error:
- (NSString*) reversingName:(NSString *)myNameText
{
NSString *result;
int len = [myNameText length];
NSMutableString *reverseName = [[NSMutableString alloc] initWithCapacity:len];
for(int i=len;i>0;i--)
{
[reverseName appendFormat:[NSString stringWithFormat:#"%c",[myNameText characterAtIndex:i]]];
}
result = reverseName;
return result;
}
The for loop line should be as follows:
for(int i=len-1;i>=0;i--)
So your method should be
- (NSString*) reversingName:(NSString *)myNameText
{
int len = [myNameText length];
NSMutableString *reverseName = [[NSMutableString alloc] initWithCapacity:len];
for(int i=len-1;i>=0;i--)
{
[reverseName appendString:[NSString stringWithFormat:#"%c",[myNameText characterAtIndex:i]]];
}
return [reverseName autorelease];
}
I thought I'd throw another version out there in case anyone's interested.. personally, I like the cleaner approach using NSMutableString but if performance is the highest priority this one is faster:
- (NSString *)reverseString:(NSString *)input {
NSUInteger len = [input length];
unichar *buffer = malloc(len * sizeof(unichar));
if (buffer == nil) return nil; // error!
[input getCharacters:buffer];
// reverse string; only need to loop through first half
for (NSUInteger stPos=0, endPos=len-1; stPos < len/2; stPos++, endPos--) {
unichar temp = buffer[stPos];
buffer[stPos] = buffer[endPos];
buffer[endPos] = temp;
}
return [[NSString alloc] initWithCharactersNoCopy:buffer length:len freeWhenDone:YES];
}
I also wrote a quick test as well to compare this with the more traditional NSMutableString method (which I also included below):
// test reversing a really large string
NSMutableString *string = [NSMutableString new];
for (int i = 0; i < 10000000; i++) {
int digit = i % 10;
[string appendFormat:#"%d", digit];
}
NSTimeInterval startTime = [[NSDate date] timeIntervalSince1970];
NSString *reverse = [self reverseString:string];
NSTimeInterval elapsedTime = [[NSDate date] timeIntervalSince1970] - startTime;
NSLog(#"reversed in %f secs", elapsedTime);
Results were:
using NSMutableString method (below) - "reversed in 3.720631 secs"
using unichar *buffer method (above) - "reversed in 0.032604 secs"
Just for reference, here's the NSMutableString method used for this comparison:
- (NSString *)reverseString:(NSString *)input {
NSUInteger len = [input length];
NSMutableString *result = [[NSMutableString alloc] initWithCapacity:len];
for (int i = len - 1; i >= 0; i--) {
[result appendFormat:#"%c", [input characterAtIndex:i]];
}
return result;
}
(NOTE: I don't have enough reputation points yet to vote or comment on answers so I'd appreciate if anyone could vote on this answer for me. I've been a long time reader but now want to start contributing more!)
try this sample code :
NSString *name = #"abcdefghi" ;
int len = [name length];
NSMutableString *reverseName = [[NSMutableString alloc] initWithCapacity:len];
for(int i=len-1;i>=0;i--)
{
[reverseName appendFormat:[NSString stringWithFormat:#"%c",[name characterAtIndex:i]]];
}
NSLog(#"%#",reverseName);
Reverse a String in Swift 2.0:
let string = "This is a test string."
let characters = string.characters
let reversedCharacters = characters.reverse()
let reversedString = String(reversedCharacters)
The short way :
String("This is a test string.".characters.reverse())
OR
let string = "This is a test string."
let array = Array(string)
let reversedArray = array.reverse()
let reversedString = String(reversedArray)
The short way :
String(Array("This is a test string.").reverse())