views:

55

answers:

2

Hello everyone,

I don't really have a solid understanding of Setters and Getters for objective-c. Can someone provide a good guide for beginners? I noticed that this comes into play when trying to access variables in another class, which I am trying to do right now. I have two classes, lets say A and B. I have a NSString variable in A with the @property (retain) NSString *variable. Then I go ahead and synthesize it. Now when the view loads in the class I set the value for the variable to "hello". Now what I want to do is access the string from class B. I have imported the the class A, and initialized it with this code:

AClass *class = [[AClass alloc] init];
NSLog(@"Value:%@", class.variable);
[class release];

However in the debugger it returns a value of "(null)", which I don't really understand. If someone could lead me into the right path I would greatly appreciate it.

Thanks,

Kevin

+1  A: 

The Getting Started with iOS guide in the iOS Reference Library outlines the reading material you should go through to nail down basics like this. Apple's guides are clearly written and thorough, and you'll be doing yourself a huge favor by hunkering down and just reading them.

No Surprises
Thanks for the link, but can you also help solve my issue with accessing class properties from a different class?
Kevin
A: 

The particular section of interest to you is Declared Properties.

b's interface should look like:

@interface b : NSObject {
    NSString *value;
}

@property (nonatomic, retain) NSString *value;

- (id) initWithValue:(NSString *)newValue;

@end

Your implementation of b should look something like:

@implementation b

@synthesize value;

- (id) initWithValue:(NSString *)newValue {
    if (self != [super init])
        return nil;

    self.value = newValue;

    return self;
}

@end

Which you could then call like:

b *test = [[b alloc] initWithValue:@"Test!"];
NSLog(@"%@", test.value);
Bill Carey
THANKS!, I'm going to go right ahead and test this.
Kevin
Do read up on the guides, though. They're very helpful for core language stuff like this.
Bill Carey