Monday, December 28, 2009

It will die: Accessing instance variables in init and dealloc

Michael, the guy behind the NSBlog, wrote a nice summery about the pros and cons of using accessors in -init* and -dealloc. He is right by pointing out the possibilities of certain side effects when using accessors in -init* and -dealloc.  On the other hand let's have a look at the near future. The Objective-C 2.0 language comes with a really nice new feature called Properties. Properties let you describe the - guess what - properties of a class very easily.

@interface Person : NSObject {
    NSString *firstName;
    NSString *lastName;
} 

@property (nonatomic, copy) NSString *firstName;
@property (nonatomic, copy) NSString *lastName;
@end

Pretty easy stuff so far. But I don't know about you but I hate redundancy in my source code. I would love to be able to just write the following piece of code:


@interface Person : NSObject
@property (nonatomic, copy) NSString *firstName;
@property (nonatomic, copy) NSString *lastName;
@end


What happened? The instance variables are gone. But the cool thing is that you can do that. The code will compile assuming the usage of the 64-bit mode. Try it! Now let's face facts: Does Apple still build 32 bit computers? No. How long will it take until there are only 64 bit computers in use? A few years maybe. This all means that instance variables will die in the near future. Nobody wants to write redundant code. Now I am asking you: How to set/release an instance variable directly when you can't access it? You simply don't.

4 comments:

  1. The instance variables are still there, they're just implicit, assuming you @synthesized them in the @implementation. (If you didn't, then you had to provide your own implementations of the property accessors anyway, and are using some other storage.) Using the latest version of Xcode, you can access these implicit instance variables by just writing their names ("firstName", "lastName") just as if you had declared them manually.

    ReplyDelete
  2. Of course they are implicitly there. By saying that they are not there I actually meant that they are missing in the @interface declaration. You say that I can access implicit instance variables by their name. This does not work here.

    http://twitpic.com/vpbz7

    ReplyDelete
  3. Accessing them directly works fine for me. Try putting the @synthesize statement at the top, rather than at the bottom.

    ReplyDelete
  4. @mike you are right. I am sorry and feel really bad right now. I didn't notice and I have to admin that what I wrote it totally wrong. Thank you very much for pointing that out.

    ReplyDelete