3

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

Eliza Wilson
  • 1,031
  • 1
  • 13
  • 38
lab12
  • 6,400
  • 21
  • 68
  • 106

2 Answers2

7

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
  • 1,395
  • 1
  • 11
  • 20
  • Do read up on the guides, though. They're very helpful for core language stuff like this. – Bill Carey Oct 21 '10 at 22:51
  • FYI, that link returns a 404 now. Is this the same article? https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html – Richard Marr Feb 03 '14 at 08:58
1

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
  • 4,831
  • 2
  • 27
  • 27
  • Thanks for the link, but can you also help solve my issue with accessing class properties from a different class? – lab12 Oct 21 '10 at 22:41