在Objective-C中,如何从类别访问私有财产 [英] in Objective-C, how to access private property from category

查看:74
本文介绍了在Objective-C中,如何从类别访问私有财产的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从类别中访问类的私有属性。

I want to access private property of a class from its category.

但是要访问私有属性,我必须重新声明类别中的同一私有属性。 >
如果我没有重新声明,我收到编译错误,属性'< property name>'找不到'< class name>类型的对象*'

But to access private property, I have to redeclare the same private property in category.
If I don't redeclare, I get a compile error, Property '<property name>' not found on object of type '<class name> *'.

这是从类别访问类私有财产的正确方法吗?

还有更好的方法要做到这一点?

Is this correct way to access private property of class from category?
And are there better ways to do this?

以下代码是私有财产在类别中重新申报的代码:

The following code is the code which private property is redeclared in category:

ClassA。 h

ClassA.h

@interface ClassA : NSObject
-(void)method1;
@end

ClassA.m

#import "ClassA.h"

// private property
@interface ClassA()
@property (nonatomic) NSString *s;
@end

@implementation ClassA
@synthesize s;

-(void)method1
{
    self.s = @"a";
    NSLog(@"%@", [NSString stringWithFormat:@"%@ - method1", self.s]);
}
@end

ClassA + Category.h

ClassA+Category.h

#import "ClassA.h"

@interface ClassA(Category)
-(void)method2;
@end

ClassA + Category.m

ClassA+Category.m

#import "ClassA+Category.h"

// redeclare private property
@interface ClassA()
@property(nonatomic) NSString *s;
@end

@implementation ClassA(Category)

-(void)method2
{
    NSLog(@"%@", [NSString stringWithFormat:@"%@ - method2", self.s]);
}
@end


为私有属性创建文件(ClassA + Private.m)并从ClassA.m和ClassA + Category.m导入它是一种好方法:

Is is good way to create a file(ClassA+Private.m) for private property and import it from ClassA.m and ClassA+Category.m:

ClassA + Private.m

ClassA+Private.m

@interface ClassA()
@property(nonatomic) NSString *s;
@end


推荐答案

解决方案的最佳方法这是创建 ClassA + Private.h 并将其导入 ClassA.m 类别.M 。记住最后的 h ,你只需要在那里声明你的私有属性和方法,定义最好保存在 ClassA.m

The best way to solve this is to create ClassA+Private.h and import it in ClassA.m and Category.m. Mind the h at the end, you only need to declare your private properties and methods there, the definition is better kept in ClassA.m.

这篇关于在Objective-C中,如何从类别访问私有财产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆