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?
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 #import
s 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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With