加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

这是在Objective-C中定义私有实例变量的新方法吗?

发布时间:2020-12-16 03:13:12 所属栏目:百科 来源:网络整理
导读:我最近更新到 Xcode 4.3.2,发现我现在可以在@implementation块中声明私有实例变量,如下所示: @interface TestClass : NSObject@property (nonatomic,copy) NSString *testProp;@end@implementation TestClass { NSString *_testPropStore;}- (NSString *)te
我最近更新到 Xcode 4.3.2,发现我现在可以在@implementation块中声明私有实例变量,如下所示:
@interface TestClass : NSObject
@property (nonatomic,copy) NSString *testProp;
@end

@implementation TestClass {
    NSString *_testPropStore;
}

- (NSString *)testProp { return _testPropStore; }
- (void)setTestProp:(NSString *)testProp { _testPropStore = [testProp copy]; }

- (id)init {
    if (self = [super init]) {
        _testPropStore = nil;
    }
    return self;
}

@end

注意在@implementation括号块内的NSString * _testPropStore行.

我也用以下代码进行了测试:

TestClass *c1 = [[TestClass alloc] init];
TestClass *c2 = [[TestClass alloc] init];

c1.testProp = @"Hello";
c2.testProp = @"World";

NSAssert(c1.testProp == c2.testProp,@"It's working!");

这似乎工作正常(也就是说,应用程序在NSAssert行中的“工作”消息崩溃.)

这是Objective-C的一个新功能,用于声明私有实例变量?由于我偶然发现这一点,我很想知道是否只是声明私有实例变量,还是会有任何我不知道的副作用?

我找不到任何相关文件,因为大多数这样类型的问题都是私人的,最后才提出了如何在私有扩展类别上声明这些问题的答案.

解决方法

这是真的,这是新的方式,*它是伟大的,是的,它在文档. The Objective-C Programming Language,尽可能接近实际的语言规范,有以下几点:

The definition of a class is structured very much like its declaration. It begins with an @implementation directive and ends with the @end directive. In addition,the class may declare instance variables in braces after the @implementation directive:

@implementation ClassName
{
    // Instance variable declarations.
}
// Method definitions.
@end

还有一个历史性的说明,从这个链接回来一点,解决了我们以前必须在接口块中声明ivars的事实:

Historically,the interface required declarations of a class’s instance variables,the data structures that are part of each instance of the class. … Instance variables represent an implementation detail,and should typically not be accessed outside of the class itself. Moreover,you can declare them in the implementation block or synthesize them using declared properties. Typically you should not,therefore,declare instance variables in the public interface and so you should omit the braces.

对于隐私问题,这些变量是真正的私有的 – 它们像在@private指令的接口中声明的ivars.这意味着默认情况下,子类无法访问它们.但是,可以使用@protected或(如果需要一些奇怪的原因)@public可以改变它们的可见性:

@interface Stuper : NSObject 
@end

@implementation Stuper
{
    @protected
    NSString * sangfroid;
}
@end

@interface Stub : Stuper
- (void)setSangfroid: (NSString *)newSangfroid;
@end

@implementation Stub

- (void)setSangfroid: (NSString *)newSangfroid {
    sangfroid = [newSangfroid copy];
}

*你必须使用clang> 3.0,我相信,就在这几个月前,这个帖子.海湾合作委员会不会这样做.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读