I have 2 classes, ClassA and ClassB
ClassA has one BOOL variable set to No.
I am trying to set this variable to Yes from ClassB, but can’t seem to figure out how to.
Below is the code I am using which doesn’t work, it is simply what I would’ve thought would work, I have stripped out the unnecessary information:
Class A:
ClassA.h
@interface AppDelegate : NSObject <NSApplicationDelegate> {
BOOL boolean;
}
- (id) init;
ClassA.m
- (id) init {
boolean = NO;
}
Class B:
ClassB.h
#import "ClassA.h"
- (IBAction) setBoolean: (id)sender;
ClassB.m
- (id) init {
ClassA * theClassA = [[ClassA alloc] init];
return self;
}
- (IBAction) setBoolean: (id)sender {
[theClassA boolean] = YES;
}
I hope this makes sense. I simply want to set the BOOL boolean in ClassA to YES from ClassB.
You can’t assign a property like that (
[object property] = value). The proper syntax is[object setProperty:value]orobject.property = value.I wouldn’t call a variable boolean. Might be misleading. Even though it’s not the keyword for a boolean variable in Objective-C it is in a lot of other languages.
And you have to return the initialized object (self) in your init method (you have an id return type, not void):
Also, you didn’t specify an instance variable for theClassA in your ClassB implementation. You just create a local object and then leak it (you don’t release it). Instead, declare it in your ClassB.h:
Then initialize it like this:
And don’t forget to release it in dealloc:
And one last thing. Having a method
- (IBAction) setBoolean: (id)senderin your ClassB implies that ClassB has a property calledboolean, which is not the case. I recommend renaming that method and/or rethinking your class designs.