NSString problems - string

I have problems with a simple NSString on Mac OS X:
NSString *letters = #"abcdefghijklmnopqrstuvwxyz0123456789";
myString = [myString stringByAppendingFormat:#"%c", [letters characterAtIndex:3]];
When I try to access this string again, Xcode is returning EXC_BAD_ACCESS
This error just occures, when I'm using the format #"%c"
When I'm using #"%#", sometimes the same error, sometimes this string: control 0x10040a480 and sometimes this:
{(
<CFRunLoopObserver 0x10015ac60 [0x7fff70731ee0]>{locked = No, valid = Yes, activities = 0x21, repeats = Yes, order = 0, callout = _ZL15FlushAllBuffersP19__CFRunLoopObservermPv (0x7fff88a147d4), context = <CFRunLoopObserver context 0x0>}
)}
The errors occur randomly even, if I don't change anything in the code and re-run it.
I try to get a random String by doing:
randomString = #"";
NSString *letters = #"abcdefghijklmnopqrstuvwxyz0123456789";
srand(time(NULL));
for (int i=0; i<5; i++)
{
randomString = [randomString stringByAppendingFormat:#"%c", [letters characterAtIndex:(rand()%[letters length])]];
}
randomString is declared in header.h
I also tried using a NSMutableString but that didn't work too.
Every time I try to access the string (or mutable string) via #"%#" I'm getting EXC_BAD_ACCESS
Any idea?
Hope somebody can help me!
Greets,
Julian

Your problem is that myString gets autoreleased before you access it.
You need to change:
myString = [myString stringByAppendingFormat:#"%c", [letters characterAtIndex:3]];
to:
myString = [[myString stringByAppendingFormat:#"%c", [letters characterAtIndex:3]] retain];
Remember to run [myString release]; when you are done with it.

this works for me:
define letters at top of file:
#define letters #"abcdefghijklmnopqrstuvwxyz0123456789"
then append a random character like this:
NSString *randomString = #"";
for (int i = 0; i < 5; i++)
{
UInt64 index = rand() % [letters length];
NSString *randomCharacter = [letters substringWithRange: NSMakeRange(index, 1)];
randomString = [randomString stringByAppendingString:randomCharacter];
}
NSLog(#"%#", randomString);

Related

Setting a random window title in C++

i wanna set my window title to a random string but i cant figure out how.
I tried to use a random string generator but i dont get how to implement it into the window title.
The random string generator i tried.
void gen_random(char *s, const int len) {
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
You have to use the _T macro to make sure that the string is in the correct format and set your title using the SetConsoleTitle function :
SetConsoleTitle(_T(*YOUR_RANDOM_TITLE_VAR*));

String/Array in Java

Does this work? I'm trying to print a message in this.
char[] tempMessage = message.toCharArray();
String[] message2 = message.split(" ");
Integer.toString(number).toCharArray();
for(int x = 0; x<newMessage.length; x++)
{
}
Although its better to use a StringBuilder, I can show it using String(s).
String[] strArr = "hello world".split("\\s+");
String s = String.valueOf(strArr[0].charAt(0))+strArr[0].length()+String.valueOf(strArr[1].charAt(0))+strArr[1].length();
Output : h5w5
String[] message2 = message.split("\\s+");
String output = "";
for(int i = 0; i < message2.length; i++)
{
output += "" + message2[i].charAt(0) + message2[i].length();
}
//output has output string.
TheLostMind's solution is already good, but I think it needs a solution for Strings of arbitrary length.
String outputString = "";
for(String x : message.split("\\s+"))
{
outputString = outputString.concat(x.charAt(0) + x.length());
}
As stated in the comments, this solution is very similiar to brso05's solution. The difference is in using the :-Operator in the for-loop. It's shorter and IMHO easier to understand, as it says 'for each String in the resulting array'.
Also, using the concat()-function is considered safer in my work environment.

Cannot access UIBezierPath in a NSMutable array

so I have a [NSMutableArray *paths] that contains UIBezierPaths that correspond to each separate path drawn on the screen. I also have another NSMutable array colors that contains the corresponding color for the path. The problem that I am having is that although the two arrays are mutating and I can see the count of both going up, the following drawRect method only seems to draw the last path in the array.
I have scoured through a lot of questions and based on what I have read so far, this very problem seems to get us newbies and mostly because of type mismatch. I even tried to Typecast the return and it was futile.
Here is my code from the drawRect
int cnt = paths.count;
if (cnt != 0)
{
for(int i = 0; i < cnt; i++)
{
NSLog(#"Drawing path:%i", i);
UIColor *color;
color = [colors objectAtIndex:i];
[color setStroke];
UIBezierPath *path = [paths objectAtIndex:i];
path.lineWidth = 2;
[path stroke];
}
}
every time I call [self setNeedsDisplay] it wipes out my entire screen.
Am I correct in assuming that I am not handling my
UIBezierPath *path = [paths objectAtIndex:i];
well?
Thank you very much and in advance.
UPDATE:
I was rummaging through some more codes and now it almost looks like there is another possibility that ARC is releasing the contents of my NSMutable array. I tried the do the following and got a compiler error.
[paths retain];
Besure you add your path to your path array afer each draw
- (void)drawRect:(CGRect)rect {
[brushPattern setStroke];
UIBezierPath *drawPath = [UIBezierPath bezierPath];
drawPath.lineCapStyle = kCGLineCapRound;
drawPath.miterLimit = 0;
drawPath.lineWidth = thisLineWidth;
for (UIBezierPath *path in pathArray)
[drawPath appendPath:path];
UIBezierPath *path = [self pathForCurrentLine];
if (path)
[drawPath appendPath:path];
[drawPath stroke];
}
- (UIBezierPath*)pathForCurrentLine {
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:startPoint];
[path addLineToPoint:endPoint];
return path;
}

how do you disable a button based on a tag?

i need assistance with this code. not sure how to write a code to disable/enable the button based on a tag.
i tried to use "[levelMenu setIsEnabled:false];" but all the buttons are disabled.
//in my init method
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:#"texture.plist"];
CCSpriteBatchNode *colorSprites = [CCSpriteBatchNode batchNodeWithFile:#"texture.png"];
[self addChild:colorSprites];
CCMenu *myMenu = [CCMenu menuWithItems:nil];
int rows = 2;
int cols = 4;
static int padding=20;
for(int count=0; count < (rows*cols); count++) {
int index1 = count +1;
NSString *spritefiles1 = [NSString stringWithFormat:#"sprite%d.png", index1];
random1 = [CCSprite spriteWithSpriteFrameName:spritefiles1];
CCMenuItemSprite *levelMenu = [CCMenuItemSprite itemFromNormalSprite:random1 selectedSprite:[CCSprite spriteWithFile:#"Iconselected.png"] disabledSprite:[CCSprite spriteWithFile:#"Iconlocked.png"] target:self selector:#selector(levelSelected:)];
int yOffset = padding+(int)(random1.contentSize.width/2-((random1.contentSize.width+padding)*(count/rows))); // or /cols to fill cols first
int xOffset = padding+(int)(random1.contentSize.width/2+((random1.contentSize.width+padding)*(count%rows))); // or %cols to fill cols first
levelMenu.position = ccp(xOffset, yOffset);
levelMenu.tag = count+1;
myMenu.position =ccp(0,300);
[myMenu addChild:levelMenu];
//testing to disable the button
// [levelMenu setIsEnabled:false];
}
-(void) levelSelected:(CCMenuItemSprite*) sender {
int level = sender.tag;
NSLog(#"test button number %d",level);
}
You may want to read this post
In Cocos2d, with buttons on multiple layers, how can I control which button to react to user's touch?
I tried, it worked for me
[_fireButton setIsEnabled:NO];

Generate string of random characters cocoa?

I know how to generate random numbers, but what I really need is a string of random characters. This is what I have so far:
NSString *letters = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789?%$";
char generated;
generated = //how do i define this?
NSLog(#"generated =%c", generated);
[textField setStringValue:generated];
-(NSString*)generateRandomString:(int)num {
NSMutableString* string = [NSMutableString stringWithCapacity:num];
for (int i = 0; i < num; i++) {
[string appendFormat:#"%C", (unichar)('a' + arc4random_uniform(25))];
}
return string;
}
then Call it like this for a 5 letter string:
NSString* string = [self generateRandomString:5];
See this SO Q & A.
Generate a random alphanumeric string in Cocoa

Resources