Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison of different ways to have private members in Objective C

I came from C++/Java world where it's quite obvious how to create private members. However, I saw several ways to do this in Objective C and I would like to hear cons and pros

1) Declare them as @private in .h file

@interface MyClass : NSObject
{
    @private
    int someMember;  
}
@end

2) Declare them in interface inside .m files

@interface MyClass() {
    int someMember;  
}
@end

@implementation MyClass
@end

3) Declare them in implementation

@implementation MyClass {
     int someMember;  
}
@end 

What is the preferred method and why? Did I miss any other methods?

like image 370
Victor Ronin Avatar asked Aug 23 '12 21:08

Victor Ronin


2 Answers

My preference is #3:

// MyClass.m
...
@implementation MyClass {
     int someMember;
}
@end

It allows you to cleanly abstract well and minimize dependencies.

Since every objc object is allocated dynamically and there is little physical dependence, you can have the fastest build times and the richest object representation minimal compilation overhead (e.g. minimal #imports and physical dependence).

Abstraction is also a huge plus -- private is the default, and there is little reason you should deviate from that, and little reason to expose the internals to others. This hides it all very nicely while ensuring type safety is not compromised. Big plus: you can also declare C++ values in your object easily without exposing everyone to all your C++ libraries' dependencies -- not PIMPL, not a struct in the global scope, not a *void**, but a proper value. it's a great compilation firewall. If you have worked on large C or C++ projects, you may rejoice.

Of course, declaring ivars as seen in option #2 brings all this. So it pretty much depends on where and how you prefer to see your variables. An ivar declaration is concrete, whereas a property may be abstracted -- so i favor grouping concrete with concrete and interface with interface but either way; #2 or #3 are ideal, unless you need backwards compatibility.

If you want (pseudo-)private properties, I recommend you declare them in the class continuation:

// MyClass.m
...
@interface MONClass ()
@property (nonatomic, copy) NSString * string;
@end
like image 60
justin Avatar answered Nov 06 '22 08:11

justin


You've conveniently listed them nearly in chronological order of addition to Objective-C.

I think this is largely a style question, but I'd say that 99% of the time:

(1) don't put them in the .h file because the .h file is effectively the published interface and there's no reason to publish implementation details;

(2) put them in the @implementation rather than in the @interface class extension on the grounds of avoiding extraneous syntax. You're always going to have an implementation, you may not have a class extension.

like image 25
Tommy Avatar answered Nov 06 '22 08:11

Tommy