类别可以访问在其扩展的类中定义的实例变量吗? [英] Can a category access instance variables defined in the class it extends?

查看:80
本文介绍了类别可以访问在其扩展的类中定义的实例变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道尝试将属性放在类别中不是一个好主意。我可以从扩展类的类别中访问类的实例变量吗?还是有必要在正在扩展的类上公开访问器?

I know it's not a great idea to try and place properties in a category. Can I access a class' instance variables from within a category that extends it? Or is it necessary to expose an accessor on the class being extended?

例如,假设我有一个名为 Person的类,其实现如下所示:

For example, let's say I have a class called "Person" and its implementation looks like this:

#import "Person.h"

@interface Person()
{
    NSMutableArray *_friends;
}
@end

@implementation Person

- (instancetype)init
{
    self = [super init];
    if (self) {
        _friends = [NSMutableArray array];
    }
    return self;
}

-(instancetype)initWithFirstname:(NSString *)firstName lastname:(NSString *)lastName
{
    self = [self init];
    if (self) {
        _firstName = firstName;
        _lastName = lastName;
    }
    return self;
}

-(NSString *)getFullName{
    return [NSString stringWithFormat:@"%@ %@", _firstName, _lastName];
}

@end

注意ivar _friends 。假设(出于某种原因)我想将与一个人的朋友打交道的所有操作都分成一个类别,例如:

Notice the ivar _friends. Let's say (for some reason or other) I wanted to segregate all operations dealing with a person's friends into a category, like so:

#import "Person.h"

@interface Person (Friends)
-(NSArray *)getFriends;
-(void)addFriend:(Person *)person;
-(void)removeFriend:(Person *)person;
@end

在类别中,人(朋友),编译器将不知道 Person 的ivar

In the category, Person(Friends), the compiler will not know about Person's ivar _friends.

//Person.h 

@interface Person
@property(nonatomic, strong) NSMutableArray *friends;
...
@end

最好不要公开此内容

推荐答案

通常,类别无法访问ivars;从类扩展名合成的ivars和ivars是私有的,在主要实现之外是不可见的。

In general, categories can't access ivars; synthesized ivars and ivars from class extensions are private and invisible outside the main implementation.

不过,您可以通过在扩展名中声明ivar来完成所需的操作。自己的专用标头,然后将该标头导入到类别的实现文件中。还要确保将私有标头导入到类的主要实现文件中。

You can, however, do what you want by declaring the ivar in an extension which is in its own private header, and importing that header into the category's implmentation file. Be sure to also import the private header into the class's main implementation file.

这篇关于类别可以访问在其扩展的类中定义的实例变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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