开发者

How to hide variables for distributed code

So I've built a few apps and am now trying my hand at building a piece of iPhone code that others can drop into their applications. Question is how do I hide the data elements in an object class header file (.h) from the user?

For example, not sure if people have used the medialets iPhone analytics but their .h does not have any data elements defined. It looks like:

#import <UIKit/UIKit.h>

@class CLLocationManager;
@class CLLocation;

@interface FlurryAPI : NSObject {
}

//miscellaneous function calls
开发者_开发技巧@end

With that header file, they also supply an assembly file (.a) that has some data elements in it. How do they maintain those data elements across the life span of the object without declaring them in the .h file?

I am not sure if it matters but the .h file is only used to create a singleton object, not multiple objects of the same class (FlurryAPI).

Any help would be much appreciated. Thanks


Take a look at this: Hide instance variable from header file in Objective C


In my header file I'd have:

@interface PublicClass : NSObject
{
}
- (void)theInt;
@end

In my source file I'd have:

@interface PrivateClass : PublicClass
{
    int theInt;
}
- (id)initPrivate;
@end;

@implementation PublicClass
- (int)theInt
{
    return 0;  // this won't get called
}
- (id)init
{
   [self release];
   self = [[PrivateClass alloc] initPrivate];
   return self;
}
- (id)initPrivate
{
   if ((self = [super init]))
   {
   }
   return self;
}
@end

@implementation PrivateClass
- (int)theInt
{
   return theInt;  // this will get called
}
- (id)initPrivate
{
   if ((self = [super initPrivate]))
   {
       theInt = 666;
   }
   return self;
}
@end

I'm using theInt as an example. Add other variables to suit your taste.


I recommend you to use categories to hide methods.

.h

#import <Foundation/Foundation.h>


@interface EncapsulationObject : NSObject {

    @private
    int value;
    NSNumber *num;
}

- (void)display;

@end

.m

#import "EncapsulationObject.h"

@interface EncapsulationObject()

@property (nonatomic) int value;
@property (nonatomic, retain) NSNumber *num;

@end


@implementation EncapsulationObject

@synthesize value;
@synthesize num;

- (id)init {

    if ((self == [super init])) {

        value = 0;
        num = [[NSNumber alloc] initWithInt:10];
    }

    return self;
}

- (void)display {

    NSLog(@"%d, %@", value, num);
}

- (void)dealloc {

    [num release];

    [super dealloc];
}

@end

You can't access to the private instance variables via dot notation, but you can still get the value by using [anObject num], though the compiler will generate a warning. This is why our apps can get rejected by Apple by calling PRIVATE APIs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜