美文网首页iOS程序猿iOS Developer
(->)指向结构体成员运算符的使用

(->)指向结构体成员运算符的使用

作者: Little_Mango | 来源:发表于2017-02-23 22:15 被阅读1585次

    (->)指向结构体成员运算符是C语言中的二目运算符,用来访问结构体中的成员。

    (->)在平时的开发中比较少用到,不过有一种情况会用到,那就是自定义类遵循NSCopying协议的时候需要实现-(id)copyWithZone:(NSZone *)zone的时候,例如:

    @interface MGClassA()<NSCopying>
    @end
    @implementation MGClassA{
        @public NSMutableArray *_friends;
    }
    
    -(id)copyWithZone:(NSZone *)zone{
        MGClassA *copy = [[self class] allocWithZone:zone];
        copy-> _friends = [_friends mutableCopy];
        return copy;
    }
    

    在上面代码中,访问实例变量是这样:
    copy-> _friends = [_friends mutableCopy];
    而不是通过(.)语法,因为实例变量不是属性(点语法的本质本章就不做解释),所以无法使用点语法。

    那么为什么要用(->) ?


    Objective-C是C\C++的超集,它的对象模型是基于类来建立的。我们可以在苹果开源的 runtime(我下载的是当前的最新版本 objc4-706.tar.gz )中发现 Objective-C 对象模型的实现细节。


    描述Objective-C对象所用的数据结构定义在objc-private.h头文件中,代码如下:

    struct objc_object {
    private:
        isa_t isa;
    
    public:
    
        // ISA() assumes this is NOT a tagged pointer object
        Class ISA();
    
        // getIsa() allows this to be a tagged pointer object
        Class getIsa();
        ...
        ...
        ...
    }
    

    该结构体只有一个成员,是个Class类型的变量,该对象定义了对象所属的类,通常成为"is a"指针。

    Objective-C 中的类本质上也是对象,我们称之为类对象,其数据结构定义在runtime.h头文件中,如下:

    typedef struct objc_class *Class;
    typedef struct objc_object *id;
    
    struct objc_class {
        Class isa  OBJC_ISA_AVAILABILITY;
    
    #if !__OBJC2__
        Class super_class                                        OBJC2_UNAVAILABLE;
        const char *name                                         OBJC2_UNAVAILABLE;
        long version                                             OBJC2_UNAVAILABLE;
        long info                                                OBJC2_UNAVAILABLE;
        long instance_size                                       OBJC2_UNAVAILABLE;
        struct objc_ivar_list *ivars                             OBJC2_UNAVAILABLE;
        struct objc_method_list **methodLists                    OBJC2_UNAVAILABLE;
        struct objc_cache *cache                                 OBJC2_UNAVAILABLE;
        struct objc_protocol_list *protocols                     OBJC2_UNAVAILABLE;
    #endif
    
    } OBJC2_UNAVAILABLE;
    

    此结构体中存放着类的元数据(metadata),描述了类对象的数据:对象的名字、版本、信息、占用的内存,类的实例实现了几个方法,有多少个实例变量,而且也描述了对象的行为:对象能够响应的消息、实现的实例方法等。因此,当我们调用实例方法 [receiver message]给一个对象发送消息时,这个对象能否响应这个消息就需要通过isa找到它所属的类,在该类的成员中的方法列表中找到目标方法,发送消息。

    类定义的实例变量存储在objc_ivar_list类型的ivars变量中,该变量存储objc_ivar类型的变量,两者的数据结构如下:

    struct objc_ivar {
        char *ivar_name                                          OBJC2_UNAVAILABLE;
        char *ivar_type                                          OBJC2_UNAVAILABLE;
        int ivar_offset                                          OBJC2_UNAVAILABLE;
    #ifdef __LP64__
        int space                                                OBJC2_UNAVAILABLE;
    #endif
    };
    
    struct objc_ivar_list {
        int ivar_count                                           OBJC2_UNAVAILABLE;
    #ifdef __LP64__
        int space                                                OBJC2_UNAVAILABLE;
    #endif
        /* variable length structure */
        struct objc_ivar ivar_list[1]                            OBJC2_UNAVAILABLE;
    };
    

    objc_ivar结构体中有一个变量int ivar_offset,它用来实例变量的偏移值,表示该变量距离存放对象的内存区域的起始地址多远。如果我们写出下面的代码:

    #import "MGSimple.h"
    
    @interface MGSimple()
    @end
    @implementation MGSimple{
        NSString *_mgName;
    }
    
    - (void)p_test{
        MGSimple *simple = self;
        simple->_mgName = @"Mango";
    }
    @end
    

    那么在clang -rewrite-objc MGSimple.m出现的C\C++代码如下:

    static void _I_MGSimple_p_test(MGSimple * self, SEL _cmd) {
        MGSimple *simple = self;
        (*(NSString **)((char *)simple + OBJC_IVAR_$_MGSimple$_mgName)) = (NSString *)&__NSConstantStringImpl__var_folders_0p_2f5648xd37q1zndk1z9kldc40000gn_T_MGSimple_5a648e_mi_0;
    }
    

    其中(char *)simple + OBJC_IVAR_$_MGSimple$_mgName)这小段代码就是拿到_mgName实例变量所在的地址。

    其中OBJC_IVAR_$_MGSimple$_mgName)是表示该实例变量的偏移值,代码如下:

    extern "C" unsigned long int OBJC_IVAR_$_MGSimple $_mgName 
    __attribute__ ((used, section ("__DATA,__objc_ivar"))) 
    = __OFFSETOFIVAR__(struct MGPerson, _arr);
    

    总的来说Objective-C中所有的类在运行时都是结构体,该结构体中有存储着实例变量,虽然实例变量不是该结构体的属性(实例变量是objc_ivar类型,存放在该结构体的objc_ivar_list变量中),但是编译器允许我们将它当做直接成员,所以可以通过(->)访问到,至于程序怎么访问实例变量,那么由底层去做。

    不过想通过(->)访问类的实例变量还有一个前提条件,那么就是要在这个实例变量所属的文件中进行访问,举个例子:

    @interface MGClassA()<NSCopying>
    @end
    @implementation MGClassA{
        @public NSMutableArray *_friends;
    }
    
    -(id)copyWithZone:(NSZone *)zone{
        MGClassA *copy = [[self class] allocWithZone:zone];
        copy-> _friends = [_friends mutableCopy]; //这样是没问题的,因为_friends是当前文件的实例变量。
        return copy;
    }
    
    @interface ViewController ()
    @end
    @implementation ViewController
    
    - (void)viewDidLoad {
        MGClassA *classA = [[self alloc] init];
        classA->_friends = @[@"Mango"];  //这里编译器会报错,因为在当前类文件中找不到_friends这个实例变量。
    }
    

    再来看一个分类的例子:

    
    #pragma mark - MGPerson.h
    
    @interface MGPerson : NSObject
    @property(nonatomic,copy,readonly)NSString *firstName;
    @property(nonatomic,copy,readonly)NSString *lastName;
    @property(nonatomic,strong,readonly)NSArray *friends;
    
    - (instancetype)initWithFirstName:(NSString *)firstName
                             lastName:(NSString *)lastName;
    @end
    
    @interface MGPerson (Friendship)
    - (void)addFriend:(MGPerson *)person;
    - (void)removeFriend:(MGPerson *)person;
    - (BOOL)isFriendWith:(MGPerson *)person;
    @end
    
    #pragma mark - MGPerson.m
    
    @interface MGPerson()
    @property(nonatomic,copy,readwrite)NSString *firstName;
    @property(nonatomic,copy,readwrite)NSString *lastName;
    
    @end
    @implementation MGPerson
    {
        NSMutableArray *_arr;
    }
          ......
    @end
    
    
    @implementation MGPerson (Friendship)
    -(void)addFriend:(MGPerson *)person{
        [_arr addObject:person];
        [self->_arr addObject:person];
    }
    
          ......
    @end
    

    在上面的代码中,在MGPerson.m文件中的一个Friendship分类中通过(->)和直接使用_arr都可以访问到MGPerson IMP中的_arr实例变量,综合上面两个例子可以得出一个结论:

    1. Objective-C将实例变量声明为static,所以在本文件中即使不在同一个IMP范围内都可以通过实例变量名访问得到。
    2. Objective-C将实例变量存储在声明为static的变量数组里,并且这个变量数组是object_class的一个成员,所以我们可以在本文件中通过objcet(->)_arr访问到实例变量。

    通过clang -rewrite-objc MGPerson.m可以看到确实如此:

    //虽然是extern,但是编译器只会在当前文件中对应实例变量是否存在
    extern "C" unsigned long int OBJC_IVAR_$_MGPerson$_arr __attribute__ ((used, section ("__DATA,__objc_ivar"))) = __OFFSETOFIVAR__(struct MGPerson, _arr);
    
    //变量数组所在的结构体确实是用static修饰。
    static struct /*_ivar_list_t*/ {
        unsigned int entsize;  // sizeof(struct _prop_t)
        unsigned int count;
        struct _ivar_t ivar_list[3];
    } _OBJC_$_INSTANCE_VARIABLES_MGPerson __attribute__ ((used, section ("__DATA,__objc_const"))) = {
        sizeof(_ivar_t),
        3,
        {{(unsigned long int *)&OBJC_IVAR_$_MGPerson$_arr, "_arr", "@\"NSMutableArray\"", 3, 8},
         {(unsigned long int *)&OBJC_IVAR_$_MGPerson$_firstName, "_firstName", "@\"NSString\"", 3, 8},
         {(unsigned long int *)&OBJC_IVAR_$_MGPerson$_lastName, "_lastName", "@\"NSString\"", 3, 8}}
    };
    

    如果本章有什么地方讲错了,还请留言指正,谢谢大家!

    相关文章

      网友评论

        本文标题:(->)指向结构体成员运算符的使用

        本文链接:https://www.haomeiwen.com/subject/botiwttx.html