(->)指向結構體成員運算符是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
實例變量,綜合上面兩個例子可以得出一個結論:
- Objective-C將實例變量聲明為static,所以在本文件中即使不在同一個IMP范圍內都可以通過實例變量名訪問得到。
- 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}}
};
如果本章有什么地方講錯了,還請留言指正,謝謝大家!