EDIT - apologies for the typo, i was in a rush, since i had to get out of the building but hmm... might i ask, why the downvotes? just because of a few syntax errors? i'm open to being critiqued, but please be constructive?
thanks for the constructive answers, i've given both an upvote.
=============================================
I have an iVar BOOL that i wanted to use throughout this class. i tried to initialize it to YES
, but the first time i read it out, it is NO
. why is that? This is strange to me because my int
s are all retained.
in my .mm
file I have something like this:
@interface MyClass : NSObject {
BOOL myBool;
int myInt;
}
@end
@implementation MyClass
-(id)init{
//...
myInt = 3;
myBool = YES; //here i set it
//...
[self addObjectsToGame];
//...
}
-(void)addObjectsToGame{
//...
assert(myInt == 3);
assert(myBool); // <---- this line would fail
//...
}
@end
i get that i can use a @property with assign, but why does this iVar not retain it's value??
EDIT
okay yeah, wow, something is really messed up here... i tried to replace it with @property
and it's still not working. i then tried to "find all in project" for the variable myBool
and i'm NOT changing it anywhere else
Note: i'm using cocos2d, but i dont think that should affect anything
I've fixed Objective-C syntax for you and everything works as expected
#import <Foundation/Foundation.h>
@interface MyClass : NSObject {
BOOL myBool;
int myInt;
}
-(void)addObjectsToGame;
@end
@implementation MyClass
-(id)init{
if (self = [super init])
{
myInt = 3;
myBool = YES; //here i set it
[self addObjectsToGame];
}
return self;
}
-(void)addObjectsToGame{
assert(myInt == 3);
assert(myBool);
NSLog(@"OK");
}
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
[MyClass new];
}
}
this iVar will retain it's value, as long as you don't do anything else to mess it up
#import <Foundation/Foundation.h>
@interface MyClass : NSObject {
BOOL myBool;
int myInt;
}
@end
@implementation MyClass
-(id)init{
//...
myInt = 3;
myBool = YES; //here i set it
//...
[self addObjectsToGame];
//...
return self;
}
-(void)addObjectsToGame{
//...
assert(myInt == 3);
assert(myBool); // <---- this line would fail
//...
NSLog(@"didn't fail");
}
@end
This code didn't fail
oh wow, i'm such a noob on iOS -
all BOOL
values initialize to NO
(rather than random), and the reason i kept getting NO
was because i had been using the BOOL
right before assigning it, and also that i had made it non-atomic
(though this won't matter most of the time)
this was the real reason; however, i'm going to accept someone else's answer seeing this is such a trivial mistake in the making
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.