【问题标题】:How to hide variables for distributed code如何隐藏分布式代码的变量
【发布时间】:2010-08-04 03:46:29
【问题描述】:

所以我已经构建了一些应用程序,现在正在尝试构建一段 iPhone 代码,其他人可以将其放入他们的应用程序中。问题是如何向用户隐藏对象类头文件 (.h) 中的数据元素?

例如,不确定人们是否使用了 medialets iPhone 分析,但他们的 .h 没有定义任何数据元素。它看起来像:

#import <UIKit/UIKit.h>

@class CLLocationManager;
@class CLLocation;

@interface FlurryAPI : NSObject {
}

//miscellaneous function calls
@end

使用该头文件,他们还提供了一个包含一些数据元素的程序集文件 (.a)。他们如何在对象的整个生命周期内维护这些数据元素而不在 .h 文件中声明它们?

我不确定这是否重要,但 .h 文件仅用于创建单例对象,而不是同一类的多个对象 (FlurryAPI)。

任何帮助将不胜感激。谢谢

【问题讨论】:

    标签: iphone objective-c


    【解决方案1】:
    【解决方案2】:

    在我的头文件中我有:

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

    在我的源文件中,我有:

    @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
    

    我以 theInt 为例。添加其他变量以适合您的口味。

    【讨论】:

      【解决方案3】:

      我建议你使用类别来隐藏方法。

      .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
      

      您无法通过点符号访问私有实例变量,但您仍然可以使用 [anObject num] 获取值,尽管编译器会生成警告。这就是为什么我们的应用可以通过调用 PRIVATE API 被 Apple 拒绝的原因。

      【讨论】:

        猜你喜欢
        • 2016-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多