FULL CLASS CODE HERE: http://pastebin.com/rdjDGLJS
EDIT: Latest code snippet taken from original posters comment
NSMutableString *spriteType;
- (void) pickSpriteType {
randomSpriteNumber = arc4random() % 2+1;
switch (randomSpriteNumber) {
case 1:
spriteType = [NSMutableString stringWithFormat:@"typeOne"];
break;
case 2:
spriteType = [NSMutableString stringWithFormat:@"typeTwo"];
break;
}
}
- (void) findSpriteNumber {
levelNumberString = [NSMutableString stringWithFormat:@"%d",levelNumber];
NSString *path = [[NSBundle mainBundle] pathForResource:@"plist_enemies" ofType:@"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
spriteNumber = [[[dict objectForKey:spriteType] objectForKey:levelNumberString] intValue];
}
- (void) initSprite {
[self moveUp];
for(int i = 0; i<spriteNumber; i++) {
if ([spriteType isEqualToString:@"typeOne"]) {
NSLog(@"repeat");
}
if ([spriteType isEqualToString:@"typeTwo"]) {
NSLog(@"repeat");
}
}
}
ORIGINAL POST:
I am using an if statement with an NString using the following code:
- (void) initSprite {
for(int i = 0; i<spriteNumber; i++) {
if (spriteType == @"typeOne") {
NSLog(@"repeat");
}
}
}
It should be logging “repeat” ‘spriteNumber’ amount of times, as long as the string ‘spriteType’ has the contents of ‘typeOne’, but nothing happens. It does not log “repeat”, but neither does it have any errors. The contents of the string ‘sprite type’ is definitely, ‘typeOne’, and spriteNumber > 0.
What can be done to fix this issue?
EDIT: I have now tried the code like this:
- (void) initSprite {
for(int i = 0; i<spriteNumber; i++) {
if ([spriteType isEqualToString:@"typeOne"]) {
NSLog(@"repeat");
}}}
It returns an error, EXC_BAD_ACCESS
EDIT: Re. retaining the value of spriteType.
It looks as if you are attempting to use spriteType as a class variable BUT you do not retain it when you set it’s value.
stringWithFormat: will return an autoreleased NSString which will not be accessible outside of the scope of the method in which it is called.
The easiest way to get spriteType to work across the whole of your class is to declare it as a @property – In both cases you will need to declare the property in your .h file & synthesise it in your .m file.
ARC
@property (nonatomic, strong) NSString* spriteType;
NON ARC – you will be responsible for releasing the value in dealloc
@property (nonatomic, retain) NSString* spriteType;
ORIGINAL:
Using == on an NSString will test if the two instances of string are indeed the same (pointer equivalence).
You need to use the NSString method isEqualToString: to test for object equivalence like this –
isEqualToString: tests the contents of the string variables against each other….