简体   繁体   中英

How to create private methods and ivars in Objective-C in iOS >= 4.0?

I've heard that lately it's possible to create private methods by declaring the interface once again in the .m file. But what exactly is the syntax like?

If it matters: Under ARC.

  • Must it appear right before @implementation?
  • Does it look exactly like the @interface declaration in the .h file?
  • Must it duplicate the information about inheritance and protocol compliance?
  • Since when is this available? What's the oldest iOS and Objc-C runtime that supports it?

Header file:

//YourClass.h:
@interface YourClass {
    @private //optional
    //private scope ivars
    @protected //default, optional
    //protected scope ivars
    @public //optional
    //public scope ivars
    @package //optional
    //package scope ivars
}

    //public methods

@end

Implementation file:

//YourClass.m:
#import "YourClass.h"

//you could also import this class extension (that's what it's called) from an
//external header file which can be helpful for making pseudo-protected methods/ivars
//Don't forget the additional import statement then, though.
@interface YourClass () <PrivateProtocol> //protocol tag optional, of cource

    @private //optional
    //private scope hidden ivars
    @protected //default, optional
    //protected scope hidden ivars
    @public //optional
    //public scope hidden ivars
    @package //optional
    //package scope hidden ivars

@end

@implementation YourClass

//your class' method implementations

@end

Docs on ivar scopes.

For more information on what's new in the above snippet and what it's all about (compatibility, etc) see the WWDC 2011 Session #322

Xcode 4.2 brought the hidden private ivars. Class extensions have been around for quite a while.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM