understanding the objective-凯发app官方网站

凯发app官方网站-凯发k8官网下载客户端中心 | | 凯发app官方网站-凯发k8官网下载客户端中心
  • 博客访问: 857000
  • 博文数量: 322
  • 博客积分: 6688
  • 博客等级: 准将
  • 技术积分: 3626
  • 用 户 组: 普通用户
  • 注册时间: 2010-09-19 11:26
文章分类

(322)

  • (1)
  • (1)
  • (2)
  • (53)
  • (1)
  • (5)
  • (2)
  • (2)
  • (3)
  • (11)
  • (21)
  • (16)
  • (1)
  • (6)
  • (38)
  • (1)
  • (1)
  • (27)
  • (0)
  • (41)
  • (0)
  • (2)
  • (2)
  • (4)
  • (18)
  • (51)
  • (2)
  • (6)
  • (1)
  • (0)
  • (1)
  • (2)
文章存档

(5)

(66)

(87)

(164)

我的朋友
相关博文
  • ·
  • ·
  • ·
  • ·
  • ·
  • ·
  • ·
  • ·
  • ·
  • ·

分类: bsd

2012-04-05 13:40:25

 

the objective-c runtime is one of the overlooked features of objective-c initially when people are generally introduced to cocoa/objective-c. the reason for this is that while objective-c (the language) is easy to pick up in only a couple hours, newcomers to cocoa spend most of their time wrapping their heads around the cocoa framework and adjusting to how it works. however the runtime is something that everybody should at least know how it works in some detail beyond knowing that code like [target domethodwith:var1]; gets translated into objc_msgsend(target,@selector(domethodwith:),var1); by the compiler. knowing what the objective-c runtime is doing will help you gain a much deeper understanding of objective-c itself and how your app is run. i think mac/iphone developers will gain something from this, regardless of your level of experience.
the objective-c runtime is open source 

the objective-c runtime is open source and available anytime from 

in fact examining the objective-c is one of the first ways i went through to figure out how it worked, beyond reading apples documentation on the matter. you can download the current version of the runtime (as of this writting) for mac os x 10.6.2 here .

dynamic vs static languages 

objective-c is a runtime oriented language, which means that when it's possible it defers decisions about what will actually be executed from compile & link time to when it's actually executing on the runtime. this gives you a lot of flexibility in that you can redirect messages to appropriate objects as you need to or you can even intentionally swap method implementations, etc. this requires the use of a runtime which can introspect objects to see what they do & don't respond to and dispatch methods appropriately. if we contrast this to a language like c. in c you start out with a main()method and then from there it's pretty much a top down design of following your logic and executing functions as you've written your code. a c struct can't forward requests to perform a function onto other targets. pretty much you have a program like so

点击(此处)折叠或打开

  1. #include <stdio.h>

  2. int main(int argc, char *argv[]) {
  3.     printf("hello world");
  4.     return 0;
  5. }

which a compiler parses, optimizes and then transforms your optimized code into assembly

.text .align 4,0x90 .globl _main _main: leh_func_begin1: pushq %rbp llabel1: movq %rsp, %rbp llabel2: subq $16, %rsp llabel3: movq %rsi, %rax movl �i, �x movl �x, -8(%rbp) movq %rax, -16(%rbp) xorb %al, %al leaq lc(%rip), %rcx movq %rcx, %rdi call _printf movl $0, -4(%rbp) movl -4(%rbp), �x addq $16, %rsp popq %rbp ret leh_func_end1: .cstring lc: .asciz "hello world!"

and then links it together with a library and produces a executable. this contrasts from objective-c in that while the process is similar the code that the compiler generates depends on the presence of the objective-c runtime library. when we are all initially introduced to objective-c we are told that (at a simplistic level) what happens to our objective-c bracket code is something like...

[self dosomethingwithvar:var1];

gets translated to...

objc_msgsend(self,@selector(dosomethingwithvar:),var1);

but beyond this we don't really know much till much later on what the runtime is doing.
what is the objective-c runtime? 

the objective-c runtime is a runtime library, it's a library written mainly in c & assembler that adds the object oriented capabilities to c to create objective-c. this means it loads in class information, does all method dispatching, method forwarding, etc. the objective-c runtime essentially creates all the support structures that make object oriented programming with objective-c possible. 

objective-c runtime terminology 

so before we go on much further, let's get some terminology out of the way so we are all on the same page about everything. 2 runtimes as far as mac & iphone developers are concerned there are 2 runtimes: the modern runtime & the legacy runtime modern runtime: covers all 64 bit mac os x apps & all iphone os apps legacy runtime: covers everything else (all 32 bit mac os x apps) method there are 2 basic types of methods. instance methods (begin with a '-' like -(void)dofoo; that operate on object instances. and class methods (begin with a ' ' like  (id)alloc. methods are just like c functions in that they are a grouping of code that performs a small task like

-(nsstring *)movietitle { return @"futurama: into the wild green yonder"; }

selector a selector in objective-c is essentially a c data struct that serves as a mean to identify an objective-c method you want an object to perform. in the runtime it's defined like so...

typedef struct objc_selector *sel;

and used like so...

sel asel = @selector(movietitle);

message

[target getmovietitleforobject:obj];

an objective-c message is everything between the 2 brackets '[ ]' and consists of the target you are sending a message to, the method you want it to perform and any arguments you are sending it. a objective-c message while similar to a c function call is different. the fact that you send a message to an object doesn't mean that it'll perform it. the object could check who the sender of the message is and based on that decide to perform a different method or forward the message onto a different target object. class if you look in the runtime for a class you'll come across this...

typedef struct objc_class *class; typedef struct objc_object { class isa; } *id;

here there are several things going on. we have a struct for an objective-c class and a struct for an object. all the objc_object has is a class pointer defined as isa, this is what we mean by the term 'isa pointer'. this isa pointer is all the objective-c runtime needs to inspect an object and see what it's class is and then begin seeing if it responds to selectors when you are messaging objects. and lastly we see the id pointer. the id pointer by default tells us nothing about objective-c objects except that they are objective-c objects. when you have a id pointer you can then ask that object for it's class, see if it responds to a method, etc and then act more specifically when you know what the object is that you are pointing to. you can see this as well on blocks in the llvm/clang docs

struct block_literal_1 { void *isa; // initialized to &_nsconcretestackblock or &_nsconcreteglobalblock int flags; int reserved; void (*invoke)(void *, ...); struct block_descriptor_1 { unsigned long int reserved; // null unsigned long int size; // sizeof(struct block_literal_1) // optional helper functions void (*copy_helper)(void *dst, void *src); void (*dispose_helper)(void *src); } *descriptor; // imported variables };

blocks themselves are designed to be compatible with the objective-c runtime so they are treated as objects so they can respond to messages like -retain,-release,-copy,etc. imp (method implementations)

typedef id (*imp)(id self,sel _cmd,...);

imp's are function pointers to the method implementations that the compiler will generate for you. if your new to objective-c you don't need to deal with these directly until much later on, but this is how the objective-c runtime invokes your methods as we'll see soon. objective-c classes so what's in an objectve-c class? the basic implementation of a class in objective-c looks like

@interface myclass : nsobject { //vars nsinteger counter; } //methods -(void)dofoo; @end

but the runtime has more than that to keep track of

#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

we can see a class has a reference to it's superclass, it's name, instance variables, methods, cache and protocols it claims to adhere to. the runtime needs this information when responding to messages that message your class or it's instances. so classes define objects and yet are objects themselves? how does this work yes earlier i said that in objective-c classes themselves are objects as well, and the runtime deals with this by creating meta classes. when you send a message like [nsobject alloc] you are actually sending a message to the class object, and that class object needs to be an instance of the metaclass which itself is an instance of the root meta class. while if you say subclass from nsobject, your class points to nsobject as it's superclass. however all meta classes point to the root metaclass as their superclass. all meta classes simply have the class methods for their method list of messages that they respond to. so when you send a message to a class object like [nsobject alloc] then objc_msgsend() actually looks through the meta class to see what it responds to then if it finds a method, operates on the class object.
why we subclass from apples classesso initially when you start cocoa development, tutorials all say to do things like subclass nsobject and start then coding something and you enjoy a lot of benefits simply by inheriting from apples classes. one thing you don't even realize that happens for you is setting your objects up to work with the objective-c runtime. when we allocate an instance of one of our classes it's done like so...

myobject *object = [[myobject alloc] init];

the very first message that gets executed is  alloc. if you  it says that "the isa instance variable of the new instance is initialized to a data structure that describes the class; memory for all other instance variables is set to 0." so by inheriting from apples classes we not only inherit some great attributes, but we inherit the ability to easily allocate and create our objects in memory that matches a structure the runtime expects (with a isa pointer that points to our class) & is the size of our class. so what's with the class cache? ( objc_cache *cache ) when the objective-c runtime inspects an object by following it's isa pointer it can find an object that implements many methods. however you may only call a small portion of them and it makes no sense to search the classes dispatch table for all the selectors every time it does a lookup. so the class implements a cache, whenever you search through a classes dispatch table and find the corresponding selector it puts that into it's cache. so when objc_msgsend() looks through a class for a selector it searches through the class cache first. this operates on the theory that if you call a message on a class once, you are likely to call that same message on it again later. so if we take this into account this means that if we have a subclass of nsobject called myobjectand run the following code

myobject *obj = [[myobject alloc] init]; @implementation myobject -(id)init { if(self = [super init]){ [self setvara:@”blah”]; } return self; } @end

the following happens (1) [myobject alloc] gets executed first. myobject class doesn't implement alloc so we will fail to find  alloc in the class and follow the superclass pointer which points to nsobject (2) we ask nsobject if it responds to  alloc and it does.  alloc checks the receiver class which is myobject and allocates a block of memory the size of our class and initializes it's isa pointer to the myobject class and we now have an instance and lastly we put  alloc in nsobject's class cache for the class object (3) up till now we were sending a class messages but now we send an instance message which simply calls -init or our designated initializer. of course our class responds to that message so -(id)init get's put into the cache (4) then self = [super init] gets called. super being a magic keyword that points to the objects superclass so we go to nsobjectand call it's init method. this is done to insure that oop inheritance works correctly in that all your super classes will initialize their variables correctly and then you (being in the subclass) can initialize your variables correctly and then override the superclasses if you really need to. in the case of nsobject, nothing of huge importance goes on, but that is not always the case. sometimes important initialization happens. take this...

#import < foundation/foundation.h> @interface myobject : nsobject { nsstring *astring; } @property(retain) nsstring *astring; @end @implementation myobject -(id)init { if (self = [super init]) { [self setastring:nil]; } return self; } @synthesize astring; @end int main (int argc, const char * argv[]) { nsautoreleasepool * pool = [[nsautoreleasepool alloc] init]; id obj1 = [nsmutablearray alloc]; id obj2 = [[nsmutablearray alloc] init]; id obj3 = [nsarray alloc]; id obj4 = [[nsarray alloc] initwithobjects:@"hello",nil]; nslog(@"obj1 class is %@",nsstringfromclass([obj1 class])); nslog(@"obj2 class is %@",nsstringfromclass([obj2 class])); nslog(@"obj3 class is %@",nsstringfromclass([obj3 class])); nslog(@"obj4 class is %@",nsstringfromclass([obj4 class])); id obj5 = [myobject alloc]; id obj6 = [[myobject alloc] init]; nslog(@"obj5 class is %@",nsstringfromclass([obj5 class])); nslog(@"obj6 class is %@",nsstringfromclass([obj6 class])); [pool drain]; return 0; }

now if you were new to cocoa and i asked you to guess as to what would be printed you'd probably say

nsmutablearray nsmutablearray nsarray nsarray myobject myobject

but this is what happens

obj1 class is __nsplaceholderarray obj2 class is nscfarray obj3 class is __nsplaceholderarray obj4 class is nscfarray obj5 class is myobject obj6 class is myobject

this is because in objective-c there is a potential for  alloc to return an object of one class and then -init to return an object of another class.
so what happens in objc_msgsend anyway? there is actually a lot that happens in objc_msgsend(). lets say we have code like this...

[self printmessagewithstring:@"hello world!"];

it actually get's translated by the compiler to...

objc_msgsend(self,@selector(printmessagewithstring:),@"hello world!");

from there we follow the target objects isa pointer to lookup and see if the object (or any of it's superclasses) respond to the selector @selector(printmessagewithstring:). assuming we find the selector in the class dispatch table or it's cache we follow the function pointer and execute it. thus objc_msgsend() never returns, it begins executing and then follows a pointer to your methods and then your methods return, thus looking like objc_msgsend() returned. bill bumgarner went into much more detail ( ,  & ) on objc_msgsend() than i will here. but to summarize what he said and what you'd see looking at the objective-c runtime code... 1. checks for ignored selectors & short circut - obviously if we are running under garbage collection we can ignore calls to -retain,-release, etc 2. check for nil target. unlike other languages messaging nil in objective-c is perfectly legal & there are some valid reasons you'd want to. assuming we have a non nil target we go on... 3. then we need to find the imp on the class, so we first search the class cache for it, if found then follow the pointer and jump to the function 4. if the imp isn't found in the cache then the class dispatch table is searched next, if it's found there follow the pointer and jump to the pointer 5. if the imp isn't found in the cache or class dispatch table then we jump to the forwarding mechanism this means in the end your code is transformed by the compiler into c functions. so a method you write like say...

-(int)docomputewithnum:(int)anum

would be transformed into...

int aclass_docomputewithnum(aclass *self,sel _cmd,int anum)

and the objective-c runtime calls your methods by invoking function pointers to those methods. now i said that you cannot call those translated methods directly, however the cocoa framework does provide a method to get at the pointer...

//declare c function pointer int (computenum *)(id,sel,int); //methodforselector is cocoa & not objc runtime //gets the same function pointer objc_msgsend gets computenum = (int (*)(id,sel,int))[target methodforselector:@selector(docomputewithnum:)]; //execute the c function pointer returned by the runtime computenum(obj,@selector(docomputewithnum:),anum);

in this way you can get direct access to the function and directly invoke it at runtime and even use this to circumvent the dynamism of the runtime if you absolutely need to make sure that a specific method is executed. this is the same way the objective-c runtime invokes your method, but using objc_msgsend().
objective-c message forwarding in objective-c it's very legal (and may even be an intentional design decision) to send messages to objects to which they don't know how to respond to. one reason apple gives for this in their docs is to simulate multiple inheritance which objective-c doesn't natively support, or you may just want to abstract your design and hide another object/class behind the scenes that deals with the message. this is one thing that the runtime is very necessary for. it works like so 1. the runtime searches through the class cache and class dispatch table of your class and all the super classes, but fails to to find the specified method 2. the objective-c runtime will call  (bool) resolveinstancemethod:(sel)aselon your class. this gives you a chance to provide a method implementation and tell the runtime that you've resolved this method and if it should begin to do it's search it'll find the method now. you could accomplish this like so... define a function...

void foomethod(id obj, sel _cmd) { nslog(@"doing foo"); }

you could then resolve it like so using class_addmethod()...

(bool)resolveinstancemethod:(sel)asel { if(asel == @selector(dofoo:)){ class_addmethod([self class],asel,(imp)foomethod,"v@:"); return yes; } return [super resolveinstancemethod]; }

the "v@:" in the last part of class_addmethod() is what the method is returning and it's arguments. you can see what you can put there in the  section of the runtime guide. 3. the runtime then calls - (id)forwardingtargetforselector:(sel)aselector. what this does is give you a chance (since we couldn't resolve the method (see #2 above)) to point the objective-c runtime at another object which should respond to the message, also this is better to do before the more expensive process of invoking - (void)forwardinvocation:(nsinvocation *)aninvocationtakes over. you could implement it like so

- (id)forwardingtargetforselector:(sel)aselector { if(aselector == @selector(mysteriousmethod:)){ return alternateobject; } return [super forwardingtargetforselector:aselector]; }

obviously you don't want to ever return self from this method or it could result in an infinite loop. 4. the runtime then tries one last time to get a message sent to it's intended target and calls - (void)forwardinvocation:(nsinvocation *)aninvocation. if you've never seen , it's essentially an objective-c message in object form. once you have an nsinvocation you essentially can change anything about the message including it's target, selector & arguments. so you could do...

-(void)forwardinvocation:(nsinvocation *)invocation { sel invsel = invocation.selector; if([altobject respondstoselector:invsel]) { [invocation invokewithtarget:altobject]; } else { [self doesnotrecognizeselector:invsel]; } }

by default if you inherit from nsobject it's - (void)forwardinvocation:(nsinvocation *)aninvocation implementation simply calls -doesnotrecognizeselector: which you could override if you wanted to for one last chance to do something about it.
non fragile ivars (modern runtime) one of the things we recently gained in the modern runtime is the concept of non fragile ivars. when compiling your classes a ivar layout is made by the compiler that shows where to access your ivars in your classes, this is the low level detail of getting a pointer to your object, seeing where the ivar is offset in relation to the beginning of the bytes the object points at, and reading in the amount of bytes that is the size of the type of variable you are reading in. so your ivar layout may look like this, with the number in the left column being the byte offset.
  



here we have the ivar layout for nsobject and then we subclass nsobject to extend it and add on our own ivars. this works fine until apple ships a update or all new mac os x 10.x release and this happens 




your custom objects get wiped out because we have an overlapping superclass. the only alternative that could prevent this is if apple sticked with the layout it had before, but if they did that then their frameworks could never advance because their ivar layouts were frozen in stone. under fragile ivars you have to recompile your classes that inherit from apples classes to restore compatibility. so what happens under non fragile ivars?
  




under non fragile ivars the compiler generates the same ivar layout as under fragile ivars. however when the runtime detects an overlapping superclass it adjusts the offsets to your additions to the class, thus your additions in a subclass are preserved.
objective-c associated objectsone thing recently introduced in mac os x 10.6 snow leopard was called associated references. objective-c has no support for dynamically adding on variables to objects unlike some other languages that have native support for this. so up until now you would have had to go to great lengths to build the infrastructure to pretend that you are adding a variable onto a class. now in mac os x 10.6, the objective-c runtime has native support for this. if we wanted to add a variable to every class that already exists like say nsview we could do so like this...

#import < cocoa/cocoa.h> //cocoa #include < objc/runtime.h> //objc runtime api’s @interface nsview (customadditions) @property(retain) nsimage *customimage; @end @implementation nsview (customadditions) static char img_key; //has a unique address (identifier) -(nsimage *)customimage { return objc_getassociatedobject(self,&img_key); } -(void)setcustomimage:(nsimage *)image { objc_setassociatedobject(self,&img_key,image, objc_association_retain); } @end

you can see in runtime.h the options for how to store the values passed to objc_setassociatedobject().

/* associated object support. */ /* objc_setassociatedobject() options */ enum { objc_association_assign = 0, objc_association_retain_nonatomic = 1, objc_association_copy_nonatomic = 3, objc_association_retain = 01401, objc_association_copy = 01403 };

these match up with the options you can pass in the @property syntax.
hybrid vtable dispatch if you look through the modern runtime code you'll come across this (in )...

/*********************************************************************** * vtable dispatch * * every class gets a vtable pointer. the vtable is an array of imps. * the selectors represented in the vtable are the same for all classes * (i.e. no class has a bigger or smaller vtable). * each vtable index has an associated trampoline which dispatches to * the imp at that index for the receiver class's vtable (after * checking for null). dispatch fixup uses these trampolines instead * of objc_msgsend. * fragility: the vtable size and list of selectors is chosen at launch * time. no compiler-generated code depends on any particular vtable * configuration, or even the use of vtable dispatch at all. * memory size: if a class's vtable is identical to its superclass's * (i.e. the class overrides none of the vtable selectors), then * the class points directly to its superclass's vtable. this means * selectors to be included in the vtable should be chosen so they are * (1) frequently called, but (2) not too frequently overridden. in * particular, -dealloc is a bad choice. * forwarding: if a class doesn't implement some vtable selector, that * selector's imp is set to objc_msgsend in that class's vtable. * initialize: each class keeps the default vtable (which always * redirects to objc_msgsend) until its initialize is completed. * otherwise, the first message to a class could be a vtable dispatch, * and the vtable trampoline doesn't include initialize checking. * changes: categories, addmethod, and setimplementation all force vtable * reconstruction for the class and all of its subclasses, if the * vtable selectors are affected. **********************************************************************/

the idea behind this is that the runtime is trying to store in this vtable the most called selectors so this in turn speeds up your app because it uses fewer instructions than objc_msgsend. this vtable is the 16 most called selectors which make up an overwheling majority of all the selectors called globally, in fact further down in the code you can see the default selectors for garbage collected & non garbage collected apps...

static const char * const defaultvtable[] = { "allocwithzone:", "alloc", "class", "self", "iskindofclass:", "respondstoselector:", "isflipped", "length", "objectforkey:", "count", "objectatindex:", "isequaltostring:", "isequal:", "retain", "release", "autorelease", }; static const char * const defaultvtablegc[] = { "allocwithzone:", "alloc", "class", "self", "iskindofclass:", "respondstoselector:", "isflipped", "length", "objectforkey:", "count", "objectatindex:", "isequaltostring:", "isequal:", "hash", "addobject:", "countbyenumeratingwithstate:objects:count:", };

so how will you know if your dealing with it? you'll see one of several methods called in your stack traces while your debugging. all of these you should basically treat just like they are objc_msgsend() for debugging purposes... objc_msgsend_fixup happens when the runtime is assigning one of these methods that your calling a slot in the vtable. objc_msgsend_fixedup occurs when your calling one of these methods that was supposed to be in the vtable but is no longer in there objc_msgsend_vtable[0-15] you'll might see a call to something like objc_msgsend_vtable5 this means you are calling one of these common methods in the vtable. the runtime can assign and unassign these as it wants to, so you shouldn't count on the fact that objc_msgsend_vtable10 corresponds to -length on one run means it'll ever be there on any of your next runs. conclusion i hope you liked this, this article essentially makes up the content i covered in my objective-c runtime talk to the  (a lot to pack in for as long a talk as we had.) the objective-c runtime is a great piece of work, it does a lot powering our cocoa/objective-c apps and makes possible so many features we just take for granted. hope i hope if you haven't yet you'll take a look through these docs apple has that show how you can take advantage of the objective-c runtime. thanks!  

阅读(750) | 评论(0) | 转发(0) |
0

上一篇:

下一篇:

给主人留下些什么吧!~~
")); function link(t){ var href= $(t).attr('href'); href ="?url=" encodeuricomponent(location.href); $(t).attr('href',href); //setcookie("returnouturl", location.href, 60, "/"); }
网站地图